How to NOT close keyboard when DONE on keyboard is pressed

自作多情 提交于 2019-12-06 17:30:29

问题


When the user presses "Done" on the soft keyboard, the keyboard closes. I want it so that it will only close if a certain condition is true (eg. the password was entered correctly).

This is my code (sets up a listener for when the "Done" button is pressed):

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;
   }
});

I realize that the reason this doesn't work is probably because it runs this code before it actually closes the soft keyboard on its own, but that's why I need help. I don't know another way.

A possible topic for answers could be working with:

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

and that sort of thing, but I don't know for sure.


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
  }
});

回答1:


if your return true from your onEditorAction method, action is not going to be handled again. In this case you can return true to not hide keyboard when action is EditorInfo.IME_ACTION_DONE.



来源:https://stackoverflow.com/questions/19458962/how-to-not-close-keyboard-when-done-on-keyboard-is-pressed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!