AlertDialog with positive button and validating custom EditText

前端 未结 1 667
忘了有多久
忘了有多久 2020-12-03 01:52

I have created simple AlertDialog with positive and negative buttons. Positive button has registered DialogInterface.OnClickListener, where I get <

相关标签:
1条回答
  • 2020-12-03 02:26

    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();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题