多次调用 onFocusChange 导致 "hasFocus" 变量不可用

onFocusChange called multiple times results in "hasFocus" variable to be unusable

我有两个 EditText 小部件,当用户在这些小部件之外单击时,我想隐藏键盘(如果当时键盘显然仍然处于活动状态)。 为此,我对它们都使用了 setOnFocusChangeListener,就像这样:

eTNom=convertView.findViewById(R.id.EditText_nom);

eTNom.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (!hasFocus) 
            hideKeyboard(v);
    }
});

另一个setOnFocusChangeListener的处理方式完全相同。

但是这不起作用,因为每次单击两个 EditText 之一时都会调用多次 (4-5) onFocusChange 方法。这导致 hasFocus 变量在调用该方法后快速在 true 和 false 之间切换,并且键盘只显示很短的时间。

这正是正在发生的事情:https://imgur.com/ZFjXPPz

我已经看到这个问题被问过一次,但接受的答案建议在清单文件中添加 android:windowSoftInputMode="adjustPan"。我这样做了,但没有解决我的问题。我还看到有人建议将 clickablefocusablefocusableInTouchMode 属性设置为 true在父布局中,我也这样做了,但它仍然不起作用。

我认为问题出在我有两个 EditText 小部件,但是当我从我的 activity 中删除一个小部件时,我仍然遇到同样的问题,所以我现在几乎迷路了非常感谢任何形式的帮助。

谢谢。

这样申请:

etTextInput.setOnFocusChangeListener((v, hasFocus) -> {
                if (hasFocus) {
                    etTextInput.removeTextChangedListener(textWatcher);
                    etTextInput.addTextChangedListener(textWatcher);
                } else {
                    etTextInput.removeTextChangedListener(textWatcher);
                }
            });

在 Manifest 的下方添加几行

<activity android:name=".ActivityName"
      android:windowSoftInputMode="stateHidden"  />

或者您可以 show/hide 使用以下两个功能的键盘

public void hideSoftKeyboard() {
    if(getCurrentFocus()!=null) {
       InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
       inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
    }
}

 /* Shows the soft keyboard */
public void showSoftKeyboard(View view) {
    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
    view.requestFocus();
    inputMethodManager.showSoftInput(view, 0);

}