我想通过点击编辑文本外部来隐藏键盘。这是我的 xml 代码:
<RelativeLayout
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true"
android:onClick="rl_main_onClick">
<RelativeLayout
//Here there are some widgets including some edittext.
</RelativeLayout>
这是我的java代码(MainActivity):
public void rl_main_onClick(View view) {
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
但我必须点击两次才能隐藏键盘。第一次点击只是将“下一步”(对于最后一个编辑文本,它是“完成”)更改为“输入”图标,然后第二次点击隐藏键盘。
这是第一次点击时发生的情况:
现在我有两个问题:
如何修复它并只需轻轻一按即可隐藏键盘?
是否可以对我的所有编辑文本执行此操作(所有代码都用一个代码)?
尝试更换onClick
with onTouch
。为此,您需要更改布局属性,如下所示:
<RelativeLayout
android:id="@+id/relativeLayout"
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true">
<RelativeLayout>
// widgets here
</RelativeLayout>
</RelativeLayout>
然后删除rl_main_onClick(View view) {...}
方法和插入onTouch
里面的监听器方法onCreate()
:
findViewById(R.id.relativeLayout).setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)