1. 程式人生 > >android中showSoftInput不起作用

android中showSoftInput不起作用

有的時候需要在介面一顯示時就讓輸入框處於焦點狀態,並且需要鍵盤彈出,方便使用者輸入。需要以下程式碼

在xml檔案中editText設定兩個屬性

android:focusable="true"
android:focusableInTouchMode="true"

顯示鍵盤
InputMethodManager manager = (InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
manager.showSoftInput(edittext, 0);
有些人會在activity或者fragment的onCreate(或者onCreateView)函式中就去呼叫上面兩行程式碼,發現並不起作用,這是因為在onCreate中或者其他宣告周期函式(onStart,onResume等)中,該EditText還未被繪製出來,InputMethodManager還不能獲取到該控制元件的焦點,所以鍵盤並不會顯示,而且manager.showSoftInput函式返回false,告訴你鍵盤並未顯示。所以只有當EditText完全被繪製出來了,才可以去獲取焦點。

解決辦法

edittext.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
      @Override
      public void onGlobalLayout() {
          InputMethodManager manager = (InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
          manager.showSoftInput(edittext, 0);
      }
});

在該段程式碼中去監聽edittext是否被繪製完畢,如果繪製完畢則呼叫onGlobalLayoutListener.onGlobalLayout函式,在該函式中去顯示鍵盤,執行下,就發現鍵盤可以正常彈出啦。哈哈,完美

隱藏鍵盤:

如何隱藏一個Activity頁面上的鍵盤:

private static void hideSoftInput(Activity actv){
        if(actv.getCurrentFocus()!=null && actv.getCurrentFocus().getWindowToken()!=null) {
            InputMethodManager manager = (InputMethodManager) actv.getSystemService(Context.INPUT_METHOD_SERVICE);
            manager.hideSoftInputFromWindow(actv.getCurrentFocus().getWindowToken(), 0);
        }
    }