Moving focus from one EditText to another

懵懂的女人 提交于 2019-12-06 16:43:38

You can listen on this action EditorInfo.IME_ACTION_NEXT for the first EditText and then request focus to the second one by this call requestFocus(), this is an example:

firstEditText.setOnEditorActionListener(new OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId,
                KeyEvent event) {

            if (actionId == EditorInfo.IME_ACTION_NEXT) {
                secondEditText.requestFocus();
                return true;
            }
            return false;
        }
    });
piojo

found a solution here

This solution works (no need to add android:focusable="true"\android:focusableInTouchMode="true"):

final EditText userEditText = (EditText)findViewById(R.id.userEditText);

userEditText.setOnFocusChangeListener(new OnFocusChangeListener() {

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if(!hasFocus){
            Log.i(TAG, "userEditText lost focus");
            if(null == m_requestFocus){
                m_userName = userEditText.getText().toString();
                if(m_userName.length() < 6){
                    m_signUpText.setText("Username should have at least 6 characters");
                    m_requestFocus = userEditText;
                }
                else{
                    checkUserNameExists();
                }
            }
        }
        else{
            if(null != m_requestFocus & m_requestFocus != userEditText){
                v.clearFocus();
                m_requestFocus.requestFocus();
                m_requestFocus = null;
            }
        }
    }
});

To clarify the problem:

User edits EditText A -> user touch EditText B to edit it -> EditText A onFocusListener.onFocusChanged is called -> EditText A requestFocus -> EditText B still has the focus and typing any text, writes to its edit text. only a marker of focus, appears on EditText A.

First of all why do you provide

android:focusable="true" android:focusableInTouchMode="true"

to layout, not to EditText field?

Second - requestFocus() definition from dev.andro: "Call this to try to give focus to a specific view or to one of its descendants."

Conclusion will be a question, because I poorly understood what you've said. This is working, focus is staying in userEditText but some other EditText is having selector for focused View?

ecdpalma

This works for me, and it looks less hackish.

What is done is send the requestFocus() in a Runnable to the process message queue. Differently from the link above, I didn't need to clear the focus of the other field and didn't need to postDelayed. My code

        new Handler().post(new Runnable() {

              @Override
              public void run() {
                   ev1.requestFocus();
              }
        });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!