I have a simple Android app that does some math on 2 numbers that the user inputs and returns the result. Currently I have a 'calculate' button that needs to be pressed to do the math and return the value.
How can I get rid of this button and just get the app to run the math after the uses has changed either one of the 2 numb开发者_C百科ers?
Many thanks.
Assuming that you are using EditText-s for the input (because they could be SeekBar-s, who knows), add on each one of them a TextWatcher with this and after each change of one of them refresh the result
I used something like this for an EditText field that I wanted to be auto-updated after changing some other EditText fields:
myEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE)
{
calculateNewValue(); // Updates internal variables
// This part will hide the keyboard after input
InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
return true;
}
return false;
}
});
This also hides the keyboard when you're done (thanks to a bit of help).
The calculateNewValue() updated the field like this:
private void calculateNewValue()
{
val = YourFormula()
myEditText.setText(String.format(yourFormat, val))
}
The details depend on what language you are using, but basically you could just run the calculation function whenever either one of the numbers is changed. There should be a way to override the function that is called when the data in either text box has changed.
Well, if both numbers start off with 0, you can either check to make sure neither or 0 or trigger the math when both text fields have received text changed events. I'm not sure what platform you are using so I can't give you much more info.
精彩评论