在AlertDialog中输入的EditText验证

时间:2014-02-01 10:19:20

标签: android android-edittext alertdialog onclicklistener

在下面的函数中,我想强制用户在EditText框“password”中输入一些文本。如果用户将其留空,我希望ALertDialog不会消失,并且可能会更改标题和消息。

我知道我需要在onClick(...)函数中执行某些操作但不能正确执行。我在SO中已经看到了其他解决方案但是没有找到确切工作的东西。感谢任何帮助,谢谢。

public void setKeywordDialog() {
    AlertDialog.Builder setPasswordDialog = new AlertDialog.Builder(this);
    setPasswordDialog.setTitle("You must set a password");
    setPasswordDialog.setMessage("Please set a password. You can change it anytime. You can receive this phone's location by texting this password");

    //Add an EditText box
    final EditText password = new EditText(this);
    password.setGravity(Gravity.CENTER);
    setPasswordDialog.setView(password);



    setPasswordDialog.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
             //<<HERE I WANT TO CHECK IF "password.getText().toString()" is empty - AlertDialogBox should not close>>

        }
    });

    setPasswordDialog.show();
}

1 个答案:

答案 0 :(得分:0)

public void setKeywordDialog() {
    AlertDialog.Builder setPasswordDialog = new AlertDialog.Builder(this);
    setPasswordDialog.setTitle("You must set a password");
    setPasswordDialog.setMessage("Please set a password. You can change it anytime. You can receive this phone's location by texting this password");

//Add an EditText box
final EditText password = new EditText(this);
password.setGravity(Gravity.CENTER);
setPasswordDialog.setView(password);



setPasswordDialog..setPositiveButton(android.R.string.ok, null);

setPasswordDialog.show();
setPasswordDialog.setOnShowListener(new DialogInterface.OnShowListener() {

@Override
public void onShow(DialogInterface dialog) {

    Button b = d.getButton(AlertDialog.BUTTON_POSITIVE);
    b.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            if(everything is ok)
            d.dismiss();
            else
            //do some changes
        }
    });
}
});
}