Could you guys lend me some fresh eyes and tell me what where I should look to find the missing link? I am trying to do a mortgage calculation by pulling value from purchasePrice, downPayment, and interestRate EditText fields to do the calculation. I tested the updateStandand() by setting the TextEdit field to interest rate. However, when I run the app in AVD, if I type a purchase price, the monthly payment field would reflect the price. If i move down to interest rate field and type in a number, the monthly payment field would change to the value of the interest rate.
Thank you!
package com.example.mortgagecalc;
import com.example.mortgagecalc.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.text.Editable;
public class Main extends Activity {
private static final String PURCHASE_AMOUNT = "PURCHASE_AMOUNT";
private static final String CUSTOM_LENGTH = "CUSTOM_LENGTH";
private static final String DOWN_PAYMENT = "DOWN_PAYMENT";
private static final String INTEREST_RATE = "INTEREST_RATE";
private int currentPurchaseAmount; //purchase amount entered by user
private int currentCustomLength; //length of loan set with SeekBar
private int currentDownPayment; //down payment entered by user
private double currentInterestRate; //interest rate entered by user
private EditText purchaseAmountEditText; //accepts user input for purchase amount
private EditText downPaymentEditText; //accepts user input for down payment amount
private EditText interestRateEditText; //accepts user input for interest rate
private EditText tenYearEditText; //display monthly payment for 10yr. loan
private EditText twentyYearEditText; //display monthly payment for 20yr. loan
private EditText thirtyYearEditText; //display monthly payment for 30yr. loan
private EditText customMonthlyEditText; //display monthly payment for custom length
private TextView customLengthTextView; //display custom loan length
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//check if app just started or being restored from memory
if (savedInstanceState == null) //app just started running
{
currentPurchaseAmount = 0; //initialize to zero
currentCustomLength = 10; //initialize custom loan length to 10
currentDownPayment = 0; //initialize to zero
currentInterestRate = 0.0; //initialize to zero
}
else
{
currentPurchaseAmount = savedInstanceState.getInt(PURCHASE_AMOUNT);
currentCustomLength = savedInstanceState.getInt(CUSTOM_LENGTH);
currentDownPayment = savedInstanceState.getInt(DOWN_PAYMENT);
currentInterestRate = savedInstanceState.getDouble(INTEREST_RATE);
}
purchaseAmountEditText = (EditText) findViewById(R.id.purchaseAmountEditText);
downPaymentEditText = (EditText) findViewById(R.id.downPaymentEditText);
interestRateEditText = (EditText) findViewById(R.id.interestRateEditText);
tenYearEditText = (EditText) findViewById(R.id.tenYearEditText);
twentyYearEditText = (EditText) findViewById(R.id.twentyYearEditText);
thirtyYearEditText = (EditText) findViewById(R.id.thirtyYearEditText);
customMonthlyEditText = (EditText) findViewById(R.id.customMonthlyEditText);
customLengthTextView = (TextView) findViewById(R.id.customMonthlyTextView);
purchaseAmountEditText.addTextChangedListener(textWatcher);
downPaymentEditText.addTextChangedListener(textWatcher);
interestRateEditText.addTextChangedListener(textWatcher);
SeekBar customSeekBar = (SeekBar) findViewById(R.id.customSeekBar);
customSeekBar.setOnSeekBarChangeListener(customSeekBarListener);
}
private void updateStandard(){
double interestRate = currentInterestRate;
//double loanPrinciple = currentPurchaseAmount - currentDownPayment;
//double tenYearMonthlyPayment = loanPrinciple;
tenYearEditText.setText(String.valueOf(interestRate));
}
private void updateCustom(){
//customLengthTextView.setText(currentCustomLength + "year");
double customInterestRate = ((currentInterestRate/12) * .01);
int customLoanPrinciple = currentPurchaseAmount - currentDownPayment;
double customMonthlyPayment = customLoanPrinciple * customInterestRate /
(1-Math.pow(1+customInterestRate, -(currentCustomLength*12)));
customMonthlyEditText.setText(Double.toString(customMonthlyPayment));
}
#Override
protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putDouble(PURCHASE_AMOUNT, currentPurchaseAmount);
outState.putDouble(DOWN_PAYMENT, currentDownPayment);
outState.putDouble(INTEREST_RATE, currentInterestRate);
outState.putDouble(CUSTOM_LENGTH, currentCustomLength);
}
private OnSeekBarChangeListener customSeekBarListener = new OnSeekBarChangeListener(){
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
{
currentCustomLength = seekBar.getProgress();
updateCustom();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar)
{
}
#Override
public void onStopTrackingTouch(SeekBar seekBar)
{
}
};
private TextWatcher textWatcher = new TextWatcher()
{
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
try
{
currentPurchaseAmount = Integer.parseInt(s.toString());
currentDownPayment = Integer.parseInt(s.toString());
currentInterestRate = Integer.parseInt(s.toString());
}
catch(NumberFormatException e)
{
currentPurchaseAmount = 0;
currentDownPayment = 0;
currentInterestRate = 0.0;
}
updateStandard();
updateCustom();
}
#Override
public void afterTextChanged(Editable s)
{
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
You're using a single TextWatcher for all three fields, and updating all three fields in the onTextChanged method.
I'm guessing that what you really want is three separate TextWatcher instances - one for each field, and to update only that one value in each one.
Related
Please guys help me! I'm going crazy ! Below is a brief summary of my code that should be used to make a simple subtraction . Should I just read the amount of SCONTRINO and if you put CONTANTI , the field VINCITE , will have as setText SCONTRINO - CONTANTI , same with VINCITE , will CONTANTI.setText SCONTRINO - VINCITE .
But despite everything seems to be well written , when I insert a field , I StackOverflowError by the two Update methods.
public class AssegnaScontoActivity extends Activity {
TextView contanti;
TextView vincite;
TextView scontrino;
Float contantiFloat;
Float vinciteFloat;
Float scontrinoFloat;
public void onCreate(Bundle savedInstanceState) {
//INIZIALIZZAZIONE ACTIVITTY
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.assegna_sconto_activity_landscape);
//--------------------------
contantiFloat = Float.parseFloat(contanti.getText().toString());
vinciteFloat = Float.parseFloat(vincite.getText().toString());
scontrinoFloat = Float.parseFloat(1000);
contanti = (TextView) findViewById(R.id.contanti);
vincite = (TextView) findViewById(R.id.importo_vincite);
scontrino = (TextView) findViewById(R.id.importo_scontrino);
contanti.addTextChangedListener(new TextChangedListener()
{
#Override
public void numberEntered(Float number)
{
contantiFloat = number;
updateVincite();
}
});
vincite.addTextChangedListener(new TextChangedListener()
{
#Override
public void numberEntered(Float number)
{
vinciteFloat = number;
updateContanti();
}
});
}
private void updateVincite()
{
Float total = scontrinoFloat - contantiFloat; // This is where you apply your function
vincite.setText(""+total); // need to do that otherwise int will
// be treated as res id.
}
private void updateContanti()
{
Float total = scontrinoFloat - vinciteFloat; // This is where you apply your function
contanti.setText(""+total); // need to do that otherwise int will
// be treated as res id.
}
private abstract class TextChangedListener implements TextWatcher
{
public abstract void numberEntered(Float number);
#Override
public void afterTextChanged(Editable s)
{
String text = s.toString();
try
{
Float parsedFloat = Float.parseFloat(text);
numberEntered(parsedFloat);
} catch (NumberFormatException e)
{
Log.w(getPackageName(), "Non si puo' parsare '" + text + "' col numero", e);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
}
Your code is going into an infinite loop because you are changing the text when afterTextChanged() is called, which causes afterTextChanged() to be called again and so on until eventually you overflow your call stack.
You can stop this by only setting the text inside updateVincite() and updateContanti() if it is different to the current text.
e.g.:
private void updateVincite()
{
Float total = scontrinoFloat - contantiFloat; // This is where you apply your function
String text = ""+total;
if(!vincite.getText().toString().contentEquals(text))
vincite.setText(text); // need to do that otherwise int will
// be treated as res id.
}
and do the same for updateContanti()
First define contanti and vincite .
Change code as follows.
contanti = (TextView) findViewById(R.id.contanti);
vincite = (TextView) findViewById(R.id.importo_vincite);
scontrino = (TextView) findViewById(R.id.importo_scontrino);
contantiFloat = Float.parseFloat(contanti.getText().toString());
vinciteFloat = Float.parseFloat(vincite.getText().toString());
scontrinoFloat = Float.parseFloat(1000);
I am nearly complete with my first android app, which is a basic tip calculator. I am having trouble with line 36
amountDisplayTextView = (TextView) findViewById(R.id.amountDisplayTextView);
I am getting these errors:
Multiple markers at this line
-Syntax error, insert ";" to complete FieldDeclaration
-Syntax error on token ".", ... expected
-Syntax error on token "amountDisplayTextView", VariableDeclaratorId expected after this token
-Return type for the method is missing
-Syntax error on token ")", { expected after this token
-Syntax error on token "amountDisplayTextView", VariableDeclaratorId expected after this token
I have tried to trouble shoot, but I hit a wall. Any assistance is appreciated! Here is the rest of the class.
package com.example.tipcalc;
import java.text.NumberFormat;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextWatcher;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
public class MainActivity extends Activity {
//currency and percent formatters
private static final NumberFormat currencyFormat =
NumberFormat.getCurrencyInstance();
private static final NumberFormat percentFormat =
NumberFormat.getPercentInstance();
private double billAmount = 0.0; //bill amount entered by the user
private double customPercent = 0.18; //initial custom percent value
private TextView amountDisplayTextView; //shows formatted bill amount
private TextView percentCustomTextView;//shows custom tip percentage
private TextView tip15TextView; // shows 15% tip
private TextView total15TextView; // shows total with 15% tip
private TextView tipCustomTextView; // shows custom tip amount
private TextView totalCustomTextView; //shows total with custom tip
//called when activity is first created
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); //call superclass's version
setContentView(R.layout.activity_main); //inflate GUI
}
//get references to the TextViews
//that MainActivity interacts with programmatically
amountDisplayTextView = (TextView) findViewById(R.id.amountDisplayTextView);
percentCustomTextView = (TextView) findViewById(R.id.percentCustomTextView);
tip15TextView = (TextView) findViewById(R.id.tip15TextView);
total15TextView = (TextView) findViewById(R.id.total15TextView);
tipCustomTextView = (TextView) findViewById(R.id.tipCustomTextView);
totalCustomTextView = (TextView) findViewById(R.id.totalCustomTextView);
}
//update 15% textviews
private void updateStandard()
{
//calculate 15% tip and total
double fifteenPercentTip = billAmount * 0.15;
double fifteenPercentTotal = billAmount + fifteenPercentTip;
//display 15% tip and total formatted as currency
tip15TextView.setText(currencyFormat.format(fifteenPercentTip));
total15TextView.setText(currencyFormat.format(fifteenPercentTotal));
} //end method updateStandard
//updates the custom tip and total TextViews
private void updateCustom()
{
//show customPercent in percentCustomTextView formatted as %
percentCustomTextView.setText(percentFormat.format(customPercent));
//calculate the custom tip and total
double customTip = billAmount * customPercent;
double customTotal = billAmount + customTip;
//display custom tip and total formatted as currency
tipCustomTextView.setText(currencyFormat.format(customTip));
totalCustomTextView.setText(currencyFormat.format(customTotal));
}//end updateCustom
//called when the user changes the position of SeekBar
private OnSeekBarChangeListener customSeekBarListener =
new OnSeekBarChangeListener()
{
//update customPercent, then call updateCustom
#Override
publicvoid onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
{
//set customPercent to position of the SeekBar's thumb
customPercent = progress / 100.0; //update the custom tip TextViews
updateCustom(); //update the custom tip TextView's
}; //end method onProgressChanged
#Override
public void onStartTrackingTouch(SeekBar seekBar)
{
}// end method onStartTrackingTouch
#Override
public void onStopTrackingTouch(SeekBar seekBar)
{
}// end method onStopTrackingTouch
};//end OnSeekBarChangeListener
//event-handling object that responds to amountEditText's events
private TextWatcher amountEditTextWatcher = new TextWatcher()
{
//called when the user enters a number
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
//convert amountEditText's text to a double
try
{
billAmount = Double.parseDouble(s.toString()) / 100.0;
} //end try
catch (NumberFormatException e)
{
billAmount = 0.0; //default if an exception occurs
}//end catch
//display currency formatted bill amount
amountDisplayTextView.setText(currencyFormat.format(billAmount));
updateStandard(); //update the 15% tip Textviews
updateCustom(); //update the custom tip TextViews
}; //end method onTextChanged
#Override
public void afterTextChanged(Editable s)
{
}//end method afterTextChanged
#Override
public void beforeTextChanged (CharSequence s, int start, int count, int after)
{
} // end method before TextChanged
}; //end amountEditTextWatcher
}//end mainActivity class
its all about your {}{} your declaring your variables at class level and trying to instantiate them too if you instantiate them inside of onCreate where they should be it will work
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); //call superclass's version
setContentView(R.layout.activity_main); //inflate GUI
//get references to the TextViews
//that MainActivity interacts with programmatically
amountDisplayTextView = (TextView) findViewById(R.id.amountDisplayTextView);
percentCustomTextView = (TextView) findViewById(R.id.percentCustomTextView);
tip15TextView = (TextView) findViewById(R.id.tip15TextView);
total15TextView = (TextView) findViewById(R.id.total15TextView);
tipCustomTextView = (TextView) findViewById(R.id.tipCustomTextView);
totalCustomTextView = (TextView) findViewById(R.id.totalCustomTextView);
}
I am having a problem with setError() on EditText. When an activity is opened, it checks if certain fields are empty and sets error message on them if true. However, the exclamation mark icon is only displayed in case I write some text in field and then delete it. If I lose focus on that field, the icon will disappear again. Both fields Naam and Telefonnumer have this validation.
I use Android 2.2.2 SDK and the application is run on Nexus 7 with latest updates.
I have Util class:
public class Util {
private static String TAG = "Util Class";
public static boolean editTextIsEmpty(EditText edittext) {
if (edittext.getText().toString().trim().length() < 1)
return true;
else
return false;
}
public void editTextListener(final EditText editText) {
editText.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (editTextIsEmpty(editText) && editText.isEnabled())
editText.setError("Nodig");
else
editText.setError(null);
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (editTextIsEmpty(editText) && editText.isEnabled())
editText.setError("Nodig");
else
editText.setError(null);
}
});
}
}
and then I have method validateInput() in my activity:
public class DeliveryActivity extends BaseActivity {
private ImageButton btnSetDate;
private Button btnToSummary;
private Button btnSearchAddress;
private EditText txtPostcode;
private EditText txtHouseNumber;
private EditText txtHouseNumberSuffix;
private EditText txtStreet;
private EditText txtCity;
private EditText txtDeliveryDate;
private EditText txtName;
private EditText txtPhone;
private EditText txtEmail;
private EditText txtRemark;
private TextView lblExtraDeliveryInfo;
private Spinner spinnerDelivery;
private Spinner spinnerDeliveryPeriod;
private Spinner spinnerContact;
private Spinner spinnerDeliveryAddress;
private Spinner spinnerExtraDeliveryInfo;
private RelativeLayout rlDeliveryAddressDetails;
private DevRestHelper additionalDeliveryInfo;
private DevRestHelper searchClientAddress;
private Util util = new Util();
private int year;
private int month;
private int day;
public static final int DIALOG_DATEPICKER = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delivery);
initControls();
validateInput();
}
private void initControls() {
btnSetDate = (ImageButton) findViewById(R.id.activity_delivery_btnCalendar);
btnToSummary = (Button) findViewById(R.id.activity_delivery_btnSummary);
btnSearchAddress = (Button) findViewById(R.id.activity_delivery_btnSearchAddress);
spinnerDelivery = (Spinner) findViewById(R.id.activity_delivery_spinnerDeliveryMethod);
spinnerDeliveryPeriod = (Spinner) findViewById(R.id.activity_delivery_spinnerDeliveryPeriod);
spinnerContact = (Spinner) findViewById(R.id.activity_delivery_spinnerContactperson);
spinnerDeliveryAddress = (Spinner) findViewById(R.id.activity_delivery_spinnerDeliveryAddress);
spinnerExtraDeliveryInfo = (Spinner) findViewById(R.id.activity_delivery_spinnerExtraDeliveryInformation);
txtPostcode = (EditText) findViewById(R.id.activity_delivery_txtPostcode);
txtHouseNumber = (EditText) findViewById(R.id.activity_delivery_txtHousenumber);
txtHouseNumberSuffix = (EditText) findViewById(R.id.activity_delivery_txtHousenumberSuffix);
txtStreet = (EditText) findViewById(R.id.activity_delivery_txtStreet);
txtCity = (EditText) findViewById(R.id.activity_delivery_txtCity);
txtDeliveryDate = (EditText) findViewById(R.id.activity_delivery_txtDeliveryDate);
txtName = (EditText) findViewById(R.id.activity_delivery_txtName);
txtPhone = (EditText) findViewById(R.id.activity_delivery_txtPhone);
txtEmail = (EditText) findViewById(R.id.activity_delivery_txtEmail);
txtRemark = (EditText) findViewById(R.id.activity_delivery_txtRemark);
lblExtraDeliveryInfo = (TextView) findViewById(R.id.activity_delivery_lblExtraDetailInformation);
rlDeliveryAddressDetails = (RelativeLayout) findViewById(R.id.activity_delivery_rlDeliveryAddressDetails);
}
private void validateInput() {
util.editTextListener(txtPostcode);
util.editTextListener(txtHouseNumber);
util.editTextListener(txtDeliveryDate);
}
}
Let me just say that code work on BlueStacks emulator.
There is a known bug with setError on Jelly Bean_MR1 (4.2 and 4.2.1). I am however assuming that the Nexus 7 you are testing with is running one of those versions of Android. See here: http://code.google.com/p/android/issues/detail?id=40417
The error will be shown while you have focus on that EditText field, but when you lose focus, the error icon is not visible to notify the user of the problem.
Before you set Error on any view or edit text, just call the
yourEditText.requestFocus();
yourEditText.setError("Your Error Message");
then set Error. it will solve your problem. Atleast mine did.
try this
new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
if (editTextIsEmpty(editText) && editText.isEnabled())
editText.setError("Nodig");
else
editText.setError(null);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// nothing here
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// nothing here
}
}
You can use following code:
May it will be helpful to you:
mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId,
com.android.internal.R.styleable.Theme_errorMessageBackground);
mView.setBackgroundResource(mPopupInlineErrorBackgroundId);
However, you can set a Spanned and a custom error icon using the overloaded setError(CharSequence, Drawable).
You can easily create a Spanned from HTML using fromHtml().
For Example:
yourEditText.setError(Html.fromHtml("<font color='blue'>this is the error</font>"));
This is the only you need to get expected setError behaviour on the TextView
android:focusable="true"
android:clickable="true"
android:focusableInTouchMode="true"
Ok,so I"m trying to make a Currency Converter between dollars and euros based on a tutorial I found on the web.The problem is that the tutorial is relying on 2 radio buttons to switch between the conversion, a reference for order stating to the program which method to call first.I want the program to make that conversion independetly from the two radio buttons and instantaneously,for instance if I write a number in the euro or dollar editText view...then clicking on the convert button will make the appropriate conversion.But I cannot because there are 2 methods and unless a have a way to display their input simultaneously it won't work.So my question is how ca I update the two editText views simultaneously when I press the convert button?Thank you
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class ConvertorActivity extends Activity {
TextView dollars;
TextView euros;
Button convert;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
dollars = (TextView)this.findViewById(R.id.dollars);
euros = (TextView)this.findViewById(R.id.euros);
convert = (Button)this.findViewById(R.id.convert);
convert.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
convertBoth();
}
});
}
public void convertBoth(){
convertDollarsToEuros();
convertEurosToDollars();
}
protected void convertDollarsToEuros() {
double val = Double.parseDouble(dollars.getText().toString());
// in a real app, we'd get this off the 'net
euros.setText(Double.toString(val*0.67));
}
protected void convertEurosToDollars() {
double val = Double.parseDouble(euros.getText().toString());
// in a real app, we'd get this off the 'net
dollars.setText(Double.toString(val/0.67));
}
}
I think what you want is this:
If the user changed the dollar amount, convert it to euro
If the user changed the euro amount, convert it to dollar
If that's the case, you can add a member variable mLastEditedViewId and use a TextWatcher to track which field was last changed. Then, onClick, call convertDollarsToEuros() or convertEurosToDollars accordingly.
In onCreate:
dollars.addTextChangedListener(new MyTextWatcher(dollars));
euros.addTextChangedListener(new MyTextWatcher(euros));
convert.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
switch (mLastEditedViewId) {
case R.id.dollars:
convertDollarsToEuros();
break;
case R.id.euros:
convertEurosToDollars();
break;
}
}
});
Define an inner class for the TextWatcher:
private class MyTextWatcher implements TextWatcher {
private int mTextViewId;
public MyTextWatcher(TextView view) {
mTextViewId = view.getId();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
mLastEditedViewId = mTextViewId;
}
public void afterTextChanged(Editable s) {
}
}
I have a project for an Android class, so I'm still learning and this should be a basic question. We were given a tip calculator and already made some modifications, now we have to add a menu.
When it starts up, it will be in multi-person mode. Gives a text box and Text Field for how many people you want the bill split into. When you hit menu, it should show a Single person mode which eliminates a text box and text field. The menu then changes to show a multi-person mode button in the menu.
I've got everything to work except it's showing both buttons, I cannot figure out how to hide a button temporarily. The main error is:
Cannot invoke setVisibility(int) on the primitive type int
on the statement:
multiple_button.setVisibility(View.GONE);
I've tried every combination of hiding the button I can think of, and think that the above line is correct, but unsure of how make it work.
one_person_button = View.VISIBLE;
multiple_button = View.GONE;
I have this in the code, but it's not doing anything either.
Any help would be greatly appreciated.
edit: code. I've read through the link, but considering I don't have a OnPrepareOptions section, I need to re-read it
package com.android;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Button;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class tipcalc extends Activity
{
public static int one_person_button = Menu.FIRST;
private int multiple_button = Menu.FIRST +1;
static final private int reset_button = Menu.FIRST +2;
private static final int MENU_ITEM = 0;
private EditText txtbillamount;
private EditText txtpeople;
private EditText txtpercentage;
private TextView txtperperson;
private TextView txttipamount;
private TextView txttotal;
private Button btncalculate;
private Button btnreset;
private double billamount = 0;
private double percentage = 0;
private double numofpeople=0;
private double tipamount = 0;
private double totaltopay = 0;
private double perperson = 0;
private View view;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuItem itemOne = menu.add(0, one_person_button, Menu.NONE,
R.string.one_person);
MenuItem itemMultiple = menu.add(1, multiple_button, Menu.NONE,
R.string.multiple);
MenuItem itemReset = menu.add(2, reset_button, Menu.NONE,
R.string.reset);
itemOne.setIcon(R.drawable.ic_menu_invite);
itemMultiple.setIcon(R.drawable.ic_menu_allfriends);
itemReset.setIcon(R.drawable.ic_menu_refresh);
one_person_button.setGroupVisible(0, true);
multiple_button.setVisibility(View.GONE);
one_person_button = View.VISIBLE;
multiple_button = View.GONE;
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if (one_person_button == View.VISIBLE) {
((TextView)findViewById(R.id.txtpeople)).setVisibility(View.INVISIBLE) ;
((TextView)findViewById(R.id.widget30)).setVisibility(View.INVISIBLE) ;
multiple_button = View.VISIBLE;
one_person_button = View.GONE;
numofpeople = 1; }
else if (multiple_button == View.VISIBLE) {
((TextView)findViewById(R.id.txtpeople)).setVisibility(View.VISIBLE) ;
((TextView)findViewById(R.id.widget30)).setVisibility(View.VISIBLE) ;
multiple_button = View.GONE;
one_person_button = View.VISIBLE;
}
return false;
}
private void initControls()
{
txtbillamount = (EditText)findViewById(R.id.txtbillamount);
txtpeople = (EditText)findViewById(R.id.txtpeople);
txtperperson=(TextView)findViewById(R.id.txtperperson);
txttipamount=(TextView)findViewById(R.id.txttipamount);
txttotal=(TextView)findViewById(R.id.txttotal);
btncalculate = (Button)findViewById(R.id.btncalculate);
btnreset = (Button)findViewById(R.id.btnreset);
btncalculate.setOnClickListener(new Button.OnClickListener() { public void onClick (View v){ calculate(); }});
btnreset.setOnClickListener(new Button.OnClickListener() { public void onClick (View v){ reset(); }});
}
private void calculate()
{
billamount=Double.parseDouble(txtbillamount.getText().toString());
numofpeople=Double.parseDouble(txtpeople.getText().toString());
RadioButton poorButton = (RadioButton) findViewById(R.id.radioButton1);
RadioButton goodButton = (RadioButton) findViewById(R.id.radioButton2);
RadioButton excellentButton = (RadioButton) findViewById(R.id.radioButton3);
if (poorButton.isChecked()){
percentage = Double.parseDouble(poorButton.getText().toString());
} else if (goodButton.isChecked()){
percentage = Double.parseDouble(goodButton.getText().toString());
} else if (excellentButton.isChecked()){
percentage = Double.parseDouble(excellentButton.getText().toString());
}
tipamount=(billamount*percentage)/100;
totaltopay=billamount+tipamount;
perperson=totaltopay/numofpeople;
txttipamount.setText(Double.toString(tipamount));
txttotal.setText(Double.toString(totaltopay));
txtperperson.setText(Double.toString(perperson));
}
private void reset()
{
txtbillamount.setText("");
txtpeople.setText("");
txtperperson.setText("");
txttipamount.setText("");
txttotal.setText("");
}
}
Post all of your relavent source code. Without it, we cannot give you specific advice about what is going wrong.
I can tell you though you'll be needing to override onPrepareOptionsMenu() and inside there you'll want to check which mode your in and make the proper button be visible. But you need to call setVisibility(View.VISIBLE); on a reference to the button widget, not on an int.
This page holds the answer to your questions.
try calling setVisibility with 8