Search code examples
androidvalidationandroid-edittextonfocus

focus on second edittext only if first is non-empty android


Currently I have two edit-text,suppose I want to make validation for empty edittext check.What is better way for runtime validation.

My code is;

    final EditText ev1 = (EditText) findViewById(R.id.editText1);
    final EditText ev2 = (EditText) findViewById(R.id.editText2);


    ev1.setOnFocusChangeListener(new OnFocusChangeListener() {

    @Override
    public void onFocusChange(View rv, boolean hasFocus) {
    if(!hasFocus && ev1.getText().length()==0)
    {    
        ev1.requestFocus();
        ev2.clearFocus();
    }
    }
});

In this onclick of second editText it clears the focus of second EditText when First Edittext is empty,but keyboard entries always done in Second Text,and we can never get focus in First Text.

Please don't suggest different different focus listener for different EditText as this editText may be added dynamically too.

Having Focus in Both Text!!!!

More CLEARLY:Just simple thing to validate ev1 before losing focus,not allow other views to get focus until any character is entered in it.


Solution

  •     final EditText ev1 = (EditText) findViewById(R.id.editText1);
        final EditText ev2 = (EditText) findViewById(R.id.editText2);
    
        ev1.setOnFocusChangeListener(new OnFocusChangeListener() {      
            @Override
            public void onFocusChange(View rv, boolean hasFocus) {
                if(!hasFocus && ev1.getText().length()==0)
                {    
                      new Handler().postDelayed(new Runnable() {
    
                      @Override
                      public void run() {
                           ev2.clearFocus();
                       ev1.requestFocus();
    
                      }
                }, 100);
    
             }
          }
        });