Reputation: 2256
Hi
In my android app, I want to get user's input from a EditText widget in AlertDialog. If the user doesn't input legal text and click the confirm button, the AlertDialog should not be closed and some response should be made, How should I do?
Here are my current code:
li = LayoutInflater.from(this);
View editNickView = li.inflate(R.layout.dialog_edit_nick,
null);
AlertDialog.Builder editNickBuilder = new AlertDialog.Builder(
this);
editNickBuilder.setTitle(R.string.edit_nick);
editNickBuilder.setView(editNickView);
AlertDialog editNick = editNickBuilder.create();
editNick.setButton(getText(R.string.com_confirm),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
AlertDialog editNick = (AlertDialog)dialog;
EditText et = (EditText)editNick.findViewById(R.id.et_nick_new);
mCurUser.setName(et.getText().toString()) ;
editNick(mCurUser);
}
});
editNick.setButton2(getText(R.string.com_cancel),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
return editNick;
thanks!
Upvotes: 4
Views: 1655
Reputation: 761
AlertDialog alway closes when one of its buttons is clicked. If you don't want this happen, do not call setButton, just put your buttons in your custom layout xml. Check the precondition and call editNick.dismiss()
to close the dialog when needed.
Some snippets might help:
View editNickView = li.inflate(R.layout.dialog_edit_nick, null);
....
final AlertDialog editNick = editNickBuilder.create();
Button button = (Button) editNickView.findViewById(R.id.your_button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
....
if(shouldClose) {
editNick.dismiss();
}
else {
//Make a toast or something here.
}
}
});
Upvotes: 4
Reputation: 25536
To do this, put your buttons in you Linear Layout OR in layout and do not use the default buttons provided by AlertDialog.
After setting the button in the XML file, you create the object of the buttons using:
Button b1 = editNickView.findViewById(<ID of button1>);
and then you create a listener for this button. Now in the listener, if you find that user has entered a correct input then call :
editNick.dismiss();
to close the dialog, otherwise, dialog will be visible to user.
Upvotes: 3