gpt4 book ai didi

android - 带有肯定按钮并验证自定义 EditText 的 AlertDialog

转载 作者:IT老高 更新时间:2023-10-28 23:27:10 24 4
gpt4 key购买 nike

我创建了带有正负按钮的简单 AlertDialog。正按钮已注册 DialogInterface.OnClickListener,我在其中获得 EditText 值。我必须验证它(例如,如果它必须不为空)并且如果值不正确,则不允许关闭此对话框。如何防止点击验证后关闭对话框?

最佳答案

对话框创建:

AlertDialog.Builder builder = new AlertDialog.Builder(YourActivity.this);
builder.setCancelable(false)
.setMessage("Please Enter data")
.setView(edtLayout) //<-- layout containing EditText
.setPositiveButton("Enter", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//All of the fun happens inside the CustomListener now.
//I had to move it to enable data validation.
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
Button theButton = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
theButton.setOnClickListener(new CustomListener(alertDialog));

自定义监听器:

class CustomListener implements View.OnClickListener {
private final Dialog dialog;
public CustomListener(Dialog dialog) {
this.dialog = dialog;
}
@Override
public void onClick(View v) {
// put your code here
String mValue = mEdtText.getText().toString();
if(validate(mValue)){
dialog.dismiss();
}else{
Toast.makeText(YourActivity.this, "Invalid data", Toast.LENGTH_SHORT).show();
}
}
}

关于android - 带有肯定按钮并验证自定义 EditText 的 AlertDialog,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11363209/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com