如何在按下键盘上的“完成”按钮时不关闭键盘

18
当用户在软键盘上按下“完成”按钮时,键盘会关闭。我希望只有在满足某些条件时(例如输入密码正确),它才会关闭。
以下是我的代码(为“完成”按钮设置监听器):
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() { 

这类东西与IT技术有关,但我不确定。


解决方案:

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个回答

25
如果您从onEditorAction方法返回true,则操作不会再次处理。 在这种情况下,当操作为EditorInfo.IME_ACTION_DONE时,您可以返回true以不隐藏键盘。请保留HTML标记。

3
好的答案。我找不到该方法应返回什么文档说明。 - Michael Yaworski
但是键盘的imeOption会改变。 - Amit Bhandari

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接