0

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?

dpant
  • 1,622
  • 19
  • 30
  • 1
    Did you try to use addTextChangedListener() ? – FedeFonto May 11 '19 at 08:14
  • @FedeFonto That's much better even though far from perfect. I wonder if InputFilter can be set on-the-fly based on each other's value. But that's another question probably. Thanks anyway. – dpant May 12 '19 at 18:14
  • @FedeFonto I've decided to update the original question. – dpant May 12 '19 at 18:35
  • Have you tried onFocusChangeListener in combination with TextWatcher to re-set the input filter to the other fields? – FedeFonto May 13 '19 at 19:15
  • @FedeFonto Haven't tried that. Is it too much to ask you for a code sample? – dpant May 14 '19 at 09:56

0 Answers0