Change Focus to EditText Android

2020-02-23 07:57发布

I have 2 EditText's on my Activity and set the maxLength to 5.

Now I want to set the focus to editText2, if the length of 5 is reached in editView1...

I tried it with:

editView1.setOnKeyListener(new OnKeyListener() {
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if(editView1.getText().length() == 5)
            editView2.requestFocus();
        return false;
    }
});

But it won't work..

5条回答
孤傲高冷的网名
2楼-- · 2020-02-23 08:05

Request focus not working on main thread i think. But i'm not sure. This is worked for me,

_edittext.post(new Runnable() {
      public void run() 
        {
           _edittext.requestFocus();
        }

});
查看更多
Bombasti
3楼-- · 2020-02-23 08:23

EdName.setOnKeyListener(new OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            System.out.println("Yes Bud");

            if(EdName.length()== 5)
            {
                    EdBin.requestFocus();

            }
                return false;


        }
    });
查看更多
别忘想泡老子
4楼-- · 2020-02-23 08:25

This works

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

editText1.setOnKeyListener(new OnKeyListener() {

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if(editText1.getText().length() == 5)
            editText2.requestFocus();
        return false;
    }
});
查看更多
叼着烟拽天下
5楼-- · 2020-02-23 08:26

Marc Juschkeits post almost was perfect for me.

But in my case i had to test if the keyevent is an action up because i have a standard text in the edittext that has the same length.

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

editText1.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View view, int i, KeyEvent keyEvent) {
            if (keyEvent.getAction() == KeyEvent.ACTION_UP) {
                if (editText1.getText().length() == 5) {
                    editText2.requestFocus();
                }
            }
            return false;
        }
    });
查看更多
SAY GOODBYE
6楼-- · 2020-02-23 08:27

In the androidmanifest.xml file add the following code in activity tag:

android:windowSoftInputMode="stateHidden"
查看更多
登录 后发表回答