2013-10-18 132 views
13

當用戶在軟鍵盤上按下「完成」時,鍵盤將關閉。我希望它只在特定條件成立時纔會關閉(例如密碼輸入正確)。如何在按下DONE鍵盤時不關閉鍵盤

這是我的代碼(設置當按下「完成」按鈕,以便監聽器):

final EditText et = (EditText)findViewById(R.id.et); 
et.setOnEditorActionListener(new OnEditorActionListener() 
{   
    @Override 
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) 
    { 
     if(actionId==EditorInfo.IME_ACTION_DONE) 
     { 
     if (et.getText().toString().equals(password)) // they entered correct 
     { 
      // log them in 
     } 
     else 
     { 
      // bring up the keyboard 
      getWindow().setSoftInputMode(
      WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); 

      Toast.makeText(Main.this, "Incorrect.", Toast.LENGTH_SHORT).show(); 
     } 
     } 
     return false; 
    } 
}); 

我知道這不工作的原因可能是因爲它之前運行這段代碼它實際上自行關閉軟鍵盤,但這就是爲什麼我需要幫助。我不知道另一種方式。

答案可能的話題可以與合作:

activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 

,諸如此類的事情,但我不知道。


SOLUTION:

EditText et = (EditText)findViewById(R.id.et); 
et.setOnEditorActionListener(new OnEditorActionListener() 
{   
    @Override 
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) 
    { 
    if(actionId==EditorInfo.IME_ACTION_DONE) 
    { 
     if (et.getText().toString().equals(password)) // they entered correct 
     { 
      // log them in 
      return false; // close the keyboard 
     } 
     else 
     { 
      Toast.makeText(Main.this, "Incorrect.", Toast.LENGTH_SHORT).show(); 
      return true; // keep the keyboard up 
     } 
    } 
    // if you don't have the return statements in the if structure above, you 
    // could put return true; here to always keep the keyboard up when the "DONE" 
    // action is pressed. But with the return statements above, it doesn't matter 
    return false; // or return true 
    } 
}); 

回答

17

如果您onEditorAction方法你的回報true,動作不會被再次處理。在這種情況下,當動作爲EditorInfo.IME_ACTION_DONE時,您可以返回true以不隱藏鍵盤。

+3

很好的答案。我找不到任何有關該方法應該返回的文檔。 –