在片段中的 EditText 外部单击关闭键盘

Close keyboard on click outside of EditText in fragment

我有一个片段,其中包含一个用于搜索输入的 EditText 和一个 ListView。我已经让搜索部分正常工作,但现在我想在用户单击 EditText 之外的屏幕时关闭键盘。我还想使用点击事件(因为它是一个 ListView,如果我不使用点击事件,用户可能会不小心点击他们不想打开的 ListView 项目)

我知道如何在 activity 中执行此操作,但对于片段来说似乎有所不同。

到目前为止我尝试过的:

当我点击时,这似乎 post "onClick true"。

如有任何帮助,我们将不胜感激。提前致谢。

如果我没看错,你可以尝试使用 OnFocusChangeListener:

yourEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            final InputMethodManager inputManager = (InputMethodManager) getAppContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            if (inputManager != null && !hasFocus) {
                inputManager.hideSoftInputFromWindow(currentFocusedView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    });

这只是一个例子,但也许它指向了正确的方向。

试试这个,

在 xml 文件中

android:clickable="true" 
android:focusableInTouchMode="true" 

创建方法。

public void hideKeyboard(View view) {
    InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

调用方法。

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

关闭软键盘的代码如下:

public static void hideSoftKeyboard(Activity activity) {
    InputMethodManager inputMethodManager = (InputMethodManager)  activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}

您可以将它放在 Utility Class 中,或者如果您在 activity 中定义它,请避免使用 activity 参数,或调用 hideSoftKeyboard(this).

您可以编写一个方法来遍历 activity 中的每个视图,并检查它是否是 EditText 的实例(如果它没有向该组件注册 setOnTouchListener,一切都会到位)。如果您想知道如何做到这一点,其实很简单。这就是你要做的,你写一个像下面这样的递归方法。

public void setupUI(View view) {

    //Set up touch listener for non-text box views to hide keyboard.
    if(!(view instanceof EditText)) {

        view.setOnTouchListener(new OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {
                hideSoftKeyboard();
                return false;
            }

        });
    }

    //If a layout container, iterate over children and seed recursion.
    if (view instanceof ViewGroup) {

        for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {

            View innerView = ((ViewGroup) view).getChildAt(i);

            setupUI(innerView);
        }
    }
}

在 SetcontentView() 之后调用此方法,将参数作为视图的 ID,例如:

RelativeLayoutPanel android:id="@+id/parent"> ... </RelativeLayout>

然后调用`setupUI(findViewById(R.id.parent))

参考:Hide keypad in android while touching outside Edit Text Area