場景:在彈窗中帶有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);
}