请求:我知道自己没有什么影响力,但请认真考虑我的答案。
问题:点击键盘外部或最小化代码时如何关闭软键盘。
解决方案:使用外部库Butterknife。
一行解决方案:
@OnClick(R.id.activity_signup_layout) public void closeKeyboard() { ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); }
更易读的解决方案:
@OnClick(R.id.activity_signup_layout)
public void closeKeyboard() {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
解释:将OnClick监听器绑定到活动的XML布局父ID上,这样点击布局(而不是编辑文本或键盘)将运行该代码片段,隐藏键盘。
示例:如果您的布局文件是R.layout.my_layout,布局ID是R.id.my_layout_id,则Butterknife绑定调用应如下所示:
(@OnClick(R.id.my_layout_id)
public void yourMethod {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
Butterknife文档链接: http://jakewharton.github.io/butterknife/
推荐使用: Butterknife可以改变你的android开发方式。建议尝试。
注意: 不使用外部库Butterknife也可以实现相同的结果。只需像上面描述的那样将OnClickListener设置为父布局即可。
getFields()
的解决方案:https://dev59.com/e2sz5IYBdhLWcg3wlY-9 - Reto