1.解決無法彈出輸入法:
在show()方法調用之前,用dialog.setView(new EditText(context))添加一個空的EditText,由於是自定義的AlertDialog,有我們指定的佈局,所以設置這個不會影響我們的功能,這樣就可以彈出輸入法了……
2.可以彈出輸入法了,但了爲了增強用戶體驗性,當dialog中含有editText時應該,在顯示dialog的同時自動彈出鍵盤:
(1) 可以在自定義的dialog中增加如下方法:
public void showKeyboard() {if(editText!=null){
//設置可獲得焦點
editText.setFocusable(true);
editText.setFocusableInTouchMode(true);
//請求獲得焦點
editText.requestFocus();
//調用系統輸入法
InputMethodManager inputManager = (InputMethodManager) editText
.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(editText, 0);
}
}
public void showKeyboard() { if(editText!=null){ //設置可獲得焦點 editText.setFocusable(true); editText.setFocusableInTouchMode(true); //請求獲得焦點 editText.requestFocus(); //調用系統輸入法 InputMethodManager inputManager = (InputMethodManager) editText .getContext().getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.showSoftInput(editText, 0); } }
其中editText爲自定義dialog中的輸入框的view
(2) 在dialog.show()後,調用這個方法顯示輸入法,由於在調用時可能dialog界面還未加載完成,editText 可能還爲空,所以需要加上一個延時任務,延遲顯示:dialog.show();
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
dialog.showKeyboard();
}
}, 200);dialog.show(); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { dialog.showKeyboard(); } }, 200);