在外部单击时,将Android软键盘隐藏在Fragment中 [英] Hide Android soft keyboard in Fragment when clicked on outside
本文介绍了在外部单击时,将Android软键盘隐藏在Fragment中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含用于输入的EditText的片段,但是现在我想在用户单击EditText之外的屏幕时关闭键盘.
I have a fragment containing an EditText for input, but now I want to close the keyboard when the user clicks on the screen outside of the EditText.
我知道如何在一个活动中执行此操作,但是对于片段来说似乎有所不同.
I know how to do this in an activity, but it seems to be different for fragments.
我正在view.onTouchListener上调用此方法
i am calling this method on view.onTouchListener
public static void hideSoftKeyboard() {
InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
}
任何人都有解决方案,谢谢
anyone have solution, thanks
推荐答案
在该片段的父活动中,重写以下方法:
In the parent Activity of the fragment override the following method:
@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);
}
在片段的布局中使用以下属性:
And in the layout of the fragment use this attribute:
android:focusableInTouchMode="true"
希望这会对您有所帮助.
Hope this will help you.
这篇关于在外部单击时,将Android软键盘隐藏在Fragment中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文