在外部点击时隐藏片段中的键盘

Meh*_*jar 6 keyboard android fragment android-fragments

我有一个包含EditText的片段用于输入,但现在我想在用户点击EditText之外的屏幕时关闭键盘.

我知道如何在一个活动中做到这一点,但对于片段来说似乎有所不同.

我在view.onTouchListener上调用此方法

public static void hideSoftKeyboard() {
InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);

inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
}
Run Code Online (Sandbox Code Playgroud)

有人有解决方案,谢谢

小智 16

在片段的父Activity中重写以下方法:

 @Override
public boolean dispatchTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        View v = getCurrentFocus();
        if ( v instanceof EditText) {
            Rect outRect = new Rect();
            v.getGlobalVisibleRect(outRect);
            if (!outRect.contains((int)event.getRawX(), (int)event.getRawY())) {
                v.clearFocus();
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
        }
    }
    return super.dispatchTouchEvent(event);
}
Run Code Online (Sandbox Code Playgroud)

并且在片段的布局中使用此属性:

android:focusableInTouchMode="true"
Run Code Online (Sandbox Code Playgroud)

希望这会帮助你.


Nit*_*eek 1

使用这个方法效果很好

public static void hideKeyBoardMethod(final Context con, final View view) {
        try {
            view.post(new Runnable() {
                @Override
                public void run() {
                    InputMethodManager imm = (InputMethodManager) con.getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
Run Code Online (Sandbox Code Playgroud)