Search code examples
androidandroid-edittextandroid-togglebutton

Keep EditText focus when tapping on buttons


I have an EditText with three toggle buttons beneath it.

I want to keep the focus on the EditText AND have the keyboard stay visible when I tap on any of the three toggles. i.e. I do not want the keyboard to hide when the focus is outside the EditText (I should not see the keyboard hide then reopen).

I've tried the following to no avail:

toggleButton.setOnFocusChangeListener(new View.OnFocusChangeListener()
    {
        @Override
        public void onFocusChange(View v, boolean hasFocus)
        {
            editText.requestFocus(); 
            // This doesn't fully work. 
            // Focus is on editText but keyboard still hides when I 
            // tap on the toggle button.
        }
    });

The EditText and ToggleButtons are in a fragment, and the parent activity has this configuration in the AndroidManifest.

<activity
        android:name=".activities.MyActivity"
        android:label="@string/m_activity"
        android:theme="@style/AppTheme.NoActionBar"
        android:windowSoftInputMode="stateHidden|adjustResize" />

What is the best way to fix this issue?


Solution

  • I think you should do that for your yourEditText, using OnFocusChangeListener

    yourEditText.setOnFocusChangeListener(new View.OnFocusChangeListener()
        {
            @Override
            public void onFocusChange(View v, boolean hasFocus)
            {
                yourEditText.requestFocus();
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT);
            }
        });
    

    This means that, you will request focus whenever it is changed for you yourEditText and you will also show keyboard.