开发者

Why do I get this strange behavior when the user clicks my submit button?

I have an activity - a form with some TextFields and the user clicks a submit button after filling all the fields. When the user touches the submit button, it should show an alert dialog, and then when user touches OK, the rest of the OnClicklistener code will execute. Currently, my code is something like this.

listener for submit/finish button:

private final OnClickListener mFinishListener = new OnClickListener() {
    public void onClick(View v) {

    displayAlert();

    // Some other things to do here. Lets say showing some other activity   

};

Alert dialog c开发者_如何学运维ode:

public void displayAlert(){
    new AlertDialog.Builder(this).setMessage("Hi , I am Alert Dialog")  
    .setTitle("My Alert")  
    .setCancelable(true)  
    .setNeutralButton(android.R.string.ok,  
       new DialogInterface.OnClickListener() {  
       public void onClick(DialogInterface dialog, int whichButton){
           finish();
       }  
       })  
    .show(); 
}

I am getting strange output. When I click the submit/finish button, it shows me the alert dialog but it disappears before I press touch the OK button. Why?


Hi this is working but don't write  finish(); after displayAlert(); function.

private final OnClickListener mFinishListener = new OnClickListener() {
@Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
         displayAlert();
         //your code // don't write finish(); here if you write
    }
};

public void displayAlert(){
    new AlertDialog.Builder(this).setMessage("Hi , I am Alert Dialog")  
    .setTitle("My Alert")  
    .setCancelable(true)  
    .setNeutralButton(android.R.string.ok,  
       new DialogInterface.OnClickListener() {  
       public void onClick(DialogInterface dialog, int whichButton){
           finish();
       }  
       })  
    .show(); 
}


The code that you wish to execute after the user clicks OK should be moved to the onClick method of the AlertDialog. Right after finish(). Otherwise it will begin executing while the dialog box is showing.


If you wish to close the dialog only

   public void onClick(DialogInterface dialog, int whichButton){
       dialog.dismiss();
   } 

If you wish to close both dialog and close activity

   public void onClick(DialogInterface dialog, int whichButton){
       dialog.dismiss();
       finish();
   } 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜