很多應用中對於一個界面比如進入搜索界面或者修改信息等等情況,為了用戶體驗應該自動彈出軟鍵盤而不是讓用戶主動點擊輸入框才彈出(因為用戶進入該界面必然是為了更改信息)。具體實現這種效果如下:
EditText editText.setFocusable(true);
editText.setFocusableInTouchMode(true);
editText.requestFocus();
MethodManager inputManager = (InputMethodManager)editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(editText, 0);
首先要對指定的輸入框請求焦點。然后調用輸入管理器彈出軟鍵盤。
特別的:對於剛跳到一個新的界面就要彈出軟鍵盤的情況,上述代碼可能由於界面未加載完全而無法彈出軟鍵盤。此時應該適當的延遲彈出軟鍵盤,如200毫秒(保證界面的數據加載完成)。實例代碼如下:
edtPay.setFocusableInTouchMode(true);
edtPay.requestFocus();
Timer timer = new Timer();
timer.schedule(new TimerTask()
{
public void run()
{
InputMethodManager inputManager = (InputMethodManager)edtPay.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(edtPay, 0);
}
},
200);