Good afternoon, I am a novice in programming, so please do not scold much if anything happens. I make a small application for business needs - the essence of the application is to calculate the visa corridors. I encountered such a problem. There is an EditText field for the day of the month, and I would like to either limit the range of values ​​depending on the month from 1 to 31, or, if the value entered is greater than possible, then the field value should be reset to default.

I would like the value to change when the focus disappears from this EditText. I tried to do so

@Override public void onFocusChange(View view, boolean b) { if (!view.hasFocus()){ if (monthId == 2 && Integer.parseInt(day.getText().toString())>28){ day.setText("28"); }else if (monthId == 4 || monthId == 5 || monthId == 9 || monthId ==11 && Integer.parseInt(day.getText().toString())>30){ day.setText("30"); } }else if (Integer.parseInt(day.getText().toString())>31){ day.setText("31"); } } 

But I cannot understand in which method the listener should be created, because, as I understand it, the algorithm is this - the field receives focus - changes occur - the field loses focus (code is executed). I would be grateful for the help.

    1 answer 1

    Try this (where 15 is the default):

     mEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { int day; try { day = Integer.parseInt(mEditText.getText().toString()); } catch (NumberFormatException e) { mEditText.setText("15"); return; } if (day < 1 || day > 31) { mEditText.setText("15"); } } } }); 

    In addition, I will write that you can also carry out the test "on the fly":

     mEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { int day; try { day = Integer.parseInt(mEditText.getText().toString()); } catch (NumberFormatException e) { mEditText.setText("15"); return; } if (day < 1 || day > 31) { mEditText.setText("15"); } } }); 
    • Thank you very much, especially on the fly. It really helped! - Denis Orlov