我目前正在尝试使用 AlertDialogs。
目前,我的 AlertDialog 中有一个 EditText,并且希望将输入限制为仅整数。我使用了一个基本的 try 和 catch block 来避免应用程序因 NumberFormatException 而崩溃。
但是,我想对其进行设置,以便当用户尝试按下输入不正确的按钮时,输入不会注册并且不会取消对话框。
UpperLimitDialog.setPositiveButton(R.string.Positive_Button, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
int RawInput = settings.getInt("UpperLimit", 12);
try {
RawInput = Integer.parseInt(input.getText().toString());
}catch (NumberFormatException se) {
Toast.makeText(SettingsMenu.this, "Non-Integer Value, No Input", Toast.LENGTH_SHORT).show();
//Here I want the app to not register the click and prevent the dialog box from closing.
}
editor.putInt("UpperLimit", RawInput);
editor.apply();
Toast.makeText(SettingsMenu.this, "Set Upper Limit to " + RawInput, Toast.LENGTH_SHORT).show();
}
});
我可以使用什么方法来实现这一点?
最佳答案
这里的基本技巧是将对话框的 setCancelable
设置为 false
并仅在输入已验证时调用 dismiss()
。
更多信息在这里:AlertDialog with positive button and validating custom EditText
关于android - 如何按 'cancel' 按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38549675/