2013-07-07 76 views
17

我有一個帶有edittext的片段。 當我點擊edittext時,鍵盤顯示出來。 問題是當我打開抽屜時,抽屜不隱藏鍵盤。 即使我切換到另一個片段,鍵盤仍然顯示。 當我打開抽屜時,如何隱藏鍵盤。導航抽屜隱藏鍵盤onDrawerOpened

我試圖把

InputMethodManager imm = 
         (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
       imm.hideSoftInputFromWindow(getWindowToken(), 0); 

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); 

兩個它沒有隱藏鍵盤。

回答

25

請使用此行代碼OPE前/關閉滑動抽屜

InputMethodManager inputMethodManager = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE); 
    inputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0); 
+0

我總是得到一個麻煩使用'Fragments'(位於'NavigationDrawer'或'ViewPager')的'EditText'中的'WindowToken'。 'Activity.getCurrentFocus()'是我錯過的一件事。非常感謝。 – shkschneider

1

問題是getWindowToken()必須從當前「持有」鍵盤的視圖中調用。這非常煩人,我同意你的看法,但這就是它的工作原理。

例如,假設EditText mEditText是當前焦點接收鍵盤按鍵的對象。那麼你的代碼是:

InputMethodManager imm = 
        (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
      imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0); 

希望它有幫助。

23

嘗試......

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    ...... 

    //Initialize 
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); 

    //Setting the actionbarToggle to drawer layout 
    drawerLayout.setDrawerListener(actionBarDrawerToggle); 

    //calling sync state is necessay or else your hamburger icon wont show up 
    actionBarDrawerToggle.syncState(); 

} 

DrawerListerner

ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.app_name, R.string.app_name) { 

     @Override 
     public void onDrawerClosed(View drawerView) { 
      // Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank 
      super.onDrawerClosed(drawerView); 
      InputMethodManager inputMethodManager = (InputMethodManager) 
        getSystemService(Context.INPUT_METHOD_SERVICE); 
      inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); 
     } 

     @Override 
     public void onDrawerOpened(View drawerView) { 
      // Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank 
      super.onDrawerOpened(drawerView); 
      InputMethodManager inputMethodManager = (InputMethodManager) 
        getSystemService(Context.INPUT_METHOD_SERVICE); 
      inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); 
     } 
    }; 

快樂編碼...

+0

非常感謝。這是解決我的問題:)) –

+0

你好先生,它給了我一個空指針異常,如果(抽屜!=空){ drawer.setDrawerListener(toggle); hideKeyboard(this); }並且我無法在android studio中使用appcompatv7對ActionBarDrawerToggle進行任何更改。請幫忙 – Pihu

+0

請檢查你的ActionBarDrawerToggle監聽器對象,如果沒有正確實現它可能容易出現空指針異常。 –