Hide Android soft keyboard in Fragment when clicked on outside(在外部单击时在 Fragment 中隐藏 Android 软键盘)
问题描述
我有一个包含用于输入的 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);
}
谁有解决办法,谢谢
推荐答案
在fragment的父Activity中重写如下方法:
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.
这篇关于在外部单击时在 Fragment 中隐藏 Android 软键盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在外部单击时在 Fragment 中隐藏 Android 软键盘
基础教程推荐
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
