0. 问题描述
今天在做项目时,发现一个问题:就是自定义dialog框中,有edittext。在dialog dismiss之后,键盘会再次弹起。
就像这样:
这是什么奇奇怪怪的bug?
1. 错误示范
最开始思考,尝试再调用隐藏键盘的方法(错误示范)
/**
* 隐藏软件盘
*/
public void hideSoftInput() {
InputMethodManager imm = (InputMethodManager)
getSystemService(INPUT_METHOD_SERVICE);
if (getCurrentFocus() != null) {
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
}
然后在"取消"和"确定",按钮监听中增加该方法(自己调用)。
发现问题依旧...于是尝试某度,暂时没发现其他人 提到二次弹起键盘的问题。
2. 解决方法
直接贴解决方法吧:
重写dialog中的dismiss方法
public class MyDialog extends Dialog {
Context context;
View view;
public MyDialog(Context context) {
super(context);
this.context = context;
}
public MyDialog(Context context, int theme, View view) {
super(context, theme);
this.context = context;
this.view = view;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(view);
this.setCanceledOnTouchOutside(false);
}
@Override
public void dismiss() {
View view = getCurrentFocus();
if (view instanceof EditText) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(INPUT_METHOD_SERVICE);
if (getCurrentFocus() != null) {
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
}
super.dismiss();//注意,super放在隐藏软键盘方法下面
}
}
然后看效果:
好的,问题解决。
继续搬砖 ...