0

In my app I have 3 editTexts like this

____  ____  ____

Lets call them et1, et2, et3 from left to right

Now when the user is on et3 and he presses back on the keyboard (provided et3 is empty) I want the focus to shift to the nearest editText on the left which is et2 here. I have been trying for quite some time but couldn't find any solution to this problem which looked trivial to me at first.

Problem is that the only way I found so far to capture the backpress event of the keyboard is by making a custom editText as said in this answer, code of which is below.

public class EditTextV2 extends EditText
{
    public EditTextV2( Context context )
    {
        super( context );
    }

    public EditTextV2( Context context, AttributeSet attribute_set )
    {
        super( context, attribute_set );
    }

    public EditTextV2( Context context, AttributeSet attribute_set, int def_style_attribute )
    {
        super( context, attribute_set, def_style_attribute );
    }

    @Override
    public boolean onKeyPreIme( int key_code, KeyEvent event )
    {
        if ( event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP )
            this.clearFocus();

        return super.onKeyPreIme( key_code, event );
    }
}

Using this way I may be able to clear the focus from the current editText but how do I shift the focus to left editText? The default behavior on android is that it move focus to the left most editText i.e et1 in my case. Is there a way? Or is there another way? Any help would be appreciated. Thanks!

varunkr
  • 5,364
  • 11
  • 50
  • 99

1 Answers1

0

Actually to force focus of an edittext you just set it as focusable in xml and then put this line of code

et2.requestFocus();

Should work

Rainmaker
  • 10,294
  • 9
  • 54
  • 89
  • I guess you didn't read the question. Where should I put this? – varunkr Jan 31 '18 at 18:15
  • how do I shift the focus? isn't that your question, man?) you put it after the line this.clearFocus() . You need of corse to get access to the edittext youwant to get focused. I didn't use custom editText so just try and see if it works as the default one in your case – Rainmaker Jan 31 '18 at 18:20
  • Getting access to that editText is the real problem. Since such callback is only accessible via extending EditText class, I don't know how to access another editText. – varunkr Jan 31 '18 at 18:24
  • I also suggest you think about using edttext.setOnFocusChangeListener, maybe you could use this listener to catch not the event of keyboeard press but when your et3 loses focus – Rainmaker Jan 31 '18 at 18:24
  • wow man, I think this might actually work. I will try this and update whatever the result is, will accept your answer if it does. Thanks! – varunkr Jan 31 '18 at 18:29