场景:在弹窗中带有EditText输入框时,当EditText获取了焦点弹出软键盘后,这个时候关闭弹窗。
我们一般的处理重写dialog的dismiss()方法
@Override
public void dismiss() {
hideSoftKeyBoard(getWindow());
super.dismiss();
}
但是这样处理是不能关闭软键盘的,当dialog执行了dismiss()方法之后收起键盘的方法就无法往下执行了。
所以我们把这部分关闭软键盘的代码,放在关闭dialog之后显示出来的页面来执行就不会受dialog关闭的影响了。
可以在dialog中提供一个接口:
private DismissListener mListener;
public void setDismissListener(DismissListener listener) {
this.mListener = listener;
}
public interface DismissListener {
void onDismiss();
}
@Override
public void dismiss() {
if (mListener != null)
mListener.onDismiss();
super.dismiss();
}
在关闭弹窗后的页面设置监听器后并实现这个接口,调用收起软键盘的代码即可!
常用的显示隐藏软键盘方式如下:
/**
* 打开软键盘
*
* @param window
*/
public static void showSoftKeyBoard(final Window window) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (window.getCurrentFocus() != null) {
InputMethodManager inputManager = (InputMethodManager) window.getContext().getSystemService(Activity.INPUT_METHOD_SERVICE);
inputManager.showSoftInputFromInputMethod(window.getCurrentFocus().getWindowToken(), 0);
}
}
}, 200);
}
public static void showSoftKeyBoard(final View v) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (v != null) {
InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);
}
}
}, 200);
}
/**
* 关闭软键盘
*
* @param window
*/
public static void hideSoftKeyBoard(final Window window) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (window.getCurrentFocus() != null) {
InputMethodManager inputManager = (InputMethodManager) window.getContext().getSystemService(Activity.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(window.getCurrentFocus().getWindowToken(), 0);
}
}
}, 200);
}
public static void hideSoftKeyBoard(final Context ctx, final View v) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
InputMethodManager imm = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}, 200);
}