android – AlertDialog帶正按鈕並驗證自定義EditText
我建立了簡單的AlertDialog,帶有正負按鈕.正按鈕已註冊DialogInterface.OnClickListener,在那裡我獲得EditText值.我必須驗證它(例如,如果它不為null),如果值不正確,不允許關閉此對話方塊.點選後如何防止關閉對話方塊驗證?
對話建立:
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(); } } }
http://stackoverflow.com/questions/11363209/alertdialog-with-positive-button-and-validating-custom-edittext