点击按钮时保持 EditText 焦点

Keep EditText focus when tapping on buttons

我有一个 EditText,其下方有三个切换按钮。

我想将注意力集中在 EditText 上,并在我点击三个开关中的任何一个时让键盘保持可见。即我不希望键盘在焦点位于 EditText 之外时隐藏(我不应该看到键盘隐藏然后重新打开)。

我尝试了以下方法但无济于事:

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.
        }
    });

EditText和ToggleButtons在一个fragment中,父activity在AndroidManifest中有这个配置。

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

解决此问题的最佳方法是什么?

我认为你应该为你的 yourEditText 使用 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);
        }
    });

这意味着,每当为您更改焦点时,您将请求焦点yourEditText并且您还将显示键盘。

您可以使用下面给出的LayoutParms.Example

1.Hide键盘

this.getWindow().setSoftInputMode
(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

2.Show 键盘

this.getWindow().setSoftInputMode
(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

如果您想了解其他选项。参考下面link。

https://developer.android.com/reference/android/view/WindowManager.LayoutParams。 html