2016-09-22 202 views
0

我的主要活動有2個EditText(用戶名和密碼)和一個按鈕(登錄)。我在按鈕下方顯示狀態。Android:在按鈕上隱藏鍵盤按

當用戶點擊按鈕時,我需要隱藏鍵盤,否則鍵盤會出現狀態信息。

所以在登錄按鈕的點擊事件,我用下面的代碼編程關閉鍵盤:

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); 

我相信上面的代碼,如果用於切換鍵盤狀態,而不是專門針對關閉它。

現在的問題是,如果鍵盤已摺疊並且用戶單擊該按鈕,則會顯示鍵盤。

我需要一個替代上述代碼,它將檢查鍵盤是否關閉,如果關閉打開它。

+0

小號查詢問答,在最上面。 http://stackoverflow.com/a/1109108/6525469 –

+0

謝謝,sharma bhai –

回答

0

試試這個:

public static final void hideKeyboard(View view, Context context) { 
    InputMethodManager inputMethodManager =(InputMethodManager)context.getSystemService(Activity.INPUT_METHOD_SERVICE); 
    inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); 
} 

鑑於發送您的按鈕:

hideKeyboard(mButtonTest,context); 
1

收銀臺下面的代碼

/** 
* Hides the soft keyboard 
*/ 
public void hideSoftKeyboard() { 
    if(getCurrentFocus()!=null) { 
     InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); 
      inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); 
    } 
} 


/** 
* Shows the soft keyboard 
*/ 
public void showSoftKeyboard(View view) { 
    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); 
    view.requestFocus(); 
    inputMethodManager.showSoftInput(view, 0); 
} 
0

嘗試:

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);