AlertDialog带有正面按钮并验证自定义EditText

时间:2012-07-06 13:34:11

标签: android android-dialog

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

2 个答案:

答案 0 :(得分:54)

创建对话框:

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));

CustomListener:

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();
        }
    }
}

答案 1 :(得分:0)

View view = getLayoutInflater().inflate(R.layout.custom_dialog, null);

EditText editTextEmail=(EditText)view.findViewById(R.id.edittext_email);

AlertDialog alertDialog = new AlertDialog.Builder(YourCurrentActivity.this)
        .setView(view)
        .setPositiveButton(R.string.lbl_ok, null)
        .setNegativeButton(R.string.lbl_cancel, null)
        .create();

alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
    @Override
    public void onShow(DialogInterface dialog) {

        Button buttonPositive = ((AlertDialog) dialog).getButton(DialogInterface.BUTTON_POSITIVE);
        buttonPositive.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
             // Do something when button positive clicked
             // Your validation is here
        });

        Button buttonNegative = ((AlertDialog) dialog).getButton(DialogInterface.BUTTON_NEGATIVE);
        buttonNegative.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                // Do something when button negative clicked
            }
        });
    }
});

    alertDialog.show();
相关问题