【发布时间】:2020-07-03 00:01:47
【问题描述】:
这是我的 AlertDialog.Builder 代码,它具有带有 EditText 的自定义视图。在 EditText 中输入值后,我希望在键盘上按 Enter 的方式与 AlertDialog.Builder 的 PositiveButton 相同。我在 XML 文件中包含了必要的“imeOptions”部分。按 Enter 时我设法执行了代码,但 AlertDialog.Builder 仍在屏幕上,并且不会像单击 AlertDialog.Builder 上的 PositiveButton 时那样关闭。
//AlertDialog to set weekly income
incomeAlert = new AlertDialog.Builder(this);
incomeInflater = this.getLayoutInflater();
incomeDialogView = incomeInflater.inflate(R.layout.activity_weekincome, null);
incomeAlert.setView(incomeDialogView);
et_WeekIncome = incomeDialogView.findViewById(R.id.ls_WeekIncome);
et_WeekIncome.setOnEditorActionListener(new EditText.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
submitIncome();
return true;
}
return false;
}
});
incomeAlert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
submitIncome();
}
});
提前感谢您的帮助。
更新:我设法通过添加另一段代码来关闭 AlertDialog.Builder,如下所示
AlertDialog incomeDialog = incomeAlert.create();
incomeDialog.show();
然后当需要解雇时,我使用
incomeDialog.dismiss();
由于AlertDialog.Builder 不提供dismiss(),我必须通过AlertDialog 创建Builder。然后我在 AlertDialog 上调用dismiss()。
感谢大家的意见。
【问题讨论】:
-
取自this answer,也许KeyboardView.OnKeyboardActionListener 是您处理按回车按钮所需要的。
-
@vMysterion ,我设法执行我想在按下回车键时运行的“submitIncome”代码。但是,我面临的问题是 AlertDialog.Builder 不会自行关闭,它会留在屏幕上,但会执行所需的操作。谢谢
-
有一种方法可以关闭 AlertDialog。我不确定您是否可以从 OnKeyListener 中调用它。如果不这样做,也许尝试将 AlertDialog 上下文传递给 OnKeyListener 并用它关闭它。
-
我试过了,AlertDialog 可以使用dismiss() 方法,但我找不到AlertDialog.Builder 的类似方法。我不确定我是否做错了什么。
-
如果我将 onKeyListener 代码块放在 foo.show() 之后,这对我有用;行
标签: java android android-alertdialog