INTRODUCTION:
I am having some trouble enforcing validation to a pair of EditText
values in an Android project. The language is Java. android:inputType="number"
is set. Both views are empty, by default.
For example, the validation rule is that editTextA
and editTextB
cannot both be zero. Ideally, the validation should be performed when the user finishes input in either view.
UPDATED QUESTION:
Here's another example. Values of editTextA
and editTextB
should sum up to 5 max.
Using TextWatcher
seems to work okay but it's far from perfect. I think the best way would be to somehow be able to restrict user input on one control based on the current value of the other. Let's say that onCreate
contains the following code:
editTextA.setFilters(new InputFilter[]{ new InputFilterMinMax("0", "5")});
editTextB.setFilters(new InputFilter[]{ new InputFilterMinMax("0", "5")});
where InputFilterMinMax
is a class that implements InputFilter
as per Is there a way to define a min and max value for EditText in Android?
Now let's assume value of editTextA
becomes 3. The max filter value of editTextB
should now be 2 instead of 5.
The question is can this be applied on-the-fly?
PART OF ORIGINAL QUESTION:
Problem 1: I tried to set a EditorActionListener
but there are just too may ways a control can lose focus and I can't get the validation code to work on all cases. I've tried:
if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_NEXT || actionId = EditorInfo.IME_ACTION_PREVIOUS) {
// get values of A and B
return (valueA+valueB>0);
}
return false;
but doesn't seem to work when the user clicks directly on another control, for example.
Problem 2: The above approach doesn't seem to work in a consistent way especially when I am trying to set an error, too. Where the setError()
should be called in the action listener?
Overall, the above approach seems clumsy. Is there any other way to perform such validation?