AlertDialog that informs of error but keep activity current
I am trying to do some EditText validation and want to use an AlertDialog when the user inputs something that is illegal.
How can I have an alert dialog pop up and tell the user what is wrong with the input and then after "OK" is pressed just go back to the same view?
I'm waiting until a "confirm" button is pressed to do validation and am already inside a button's onClickListener in an Activity like so:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_progress);
//
// user adds info to progress screen
// clicks confirm when done
//
Button confirmButton = (Button) findViewById(R.id.confirm);
confirmButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// do validation code here
//
AlertDialog alert = new AlertDialog.Builder(AddStudentProgress.this).create();
alert.setTitle("Oops");
alert.setMessage("Inputs Can't be Empty");
alert.setButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// I reall want to go back to the Activity and not really do anything
}});
if ( (mScoreText.getText().toString().equals("") )) {
alert.show();
}
else {
// validation looks ok, continue
}
Am I going about this the wrong way? What should I be doing of I want to v开发者_开发知识库alidate input?
Thanks in advance, Martin
An AlertDialog is not the best way to alert your user of form errors. You can highlight the error on the field itself, with a helpful message:
if ( (mScoreText.getText().toString().equals("") )) {
mScoreText.requestFocus();
mScoreText.setError("Please enter your name");
}
This way, the user doesn't need to dismiss an alert, and they can see the error in context.
The following piece will do the trick
alert.setButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}});
精彩评论