EditText request focus not working

后端 未结 11 600
自闭症患者
自闭症患者 2020-12-15 17:03

I have an EditText and a Button. On click of the button i want to open the EditText keyboard and at the same time request focus on the

11条回答
  •  囚心锁ツ
    2020-12-15 17:11

    In my case none of the answers above worked (they don't work in Nox, for example). To set focus to EditText, you could trick it into thinking that the user actually clicked it.

    So I use MotionEvent, like this:

    // simulate a click, which consists of ACTION_DOWN and ACTION_UP
    MotionEvent eventDown = MotionEvent.obtain(System.currentTimeMillis(), System.currentTimeMillis(), MotionEvent.ACTION_DOWN, 0, 0, 0);
    editText.dispatchTouchEvent(eventDown);
    eventDown.recycle();
    
    MotionEvent eventUp = MotionEvent.obtain(System.currentTimeMillis(), System.currentTimeMillis(), MotionEvent.ACTION_UP, 0, 0, 0);
    editText.dispatchTouchEvent(eventUp);
    eventUp.recycle();
    
    // To be on the safe side, also use another method
    editText.setFocusableInTouchMode(true);
    editText.requestFocus();
    editText.requestFocusFromTouch();
    

提交回复
热议问题