AlertDialog with positive button and validating custom EditText

青春壹個敷衍的年華 提交于 2019-11-27 12:51:01

Dialog creation:

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();
        }
    }
}
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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!