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