我想通过在 edittext 之外点击来隐藏键盘。这是我的 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
替换为 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) {...}
方法并在 onCreate()
中插入 onTouch
监听器方法:
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;
}
});
关于android - 如何通过在编辑文本外轻按一下来隐藏键盘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40452321/