开发者

Android AlertDialog.Builder in switch statement

I think that the titles says it all. I'm new into Android and JAVA and I want to know if it's possible to use the AlertDialog.Builder into a switch statement.

So for example, how can I use it here:

case Activity.RESULT_OK:

break;

I just want to let the user know that action is finished and 开发者_如何学JAVAsuccessful and he just needs to press the "Ok" button.

Thanks a lot!

PS: I already imported:

import android.app.AlertDialog.Builder;


It could be as simple as you want... for instance:

case Activity.RESULT_OK:
new AlertDialog.Builder(this)
                .setMessage("Message")
                .setPositiveButton("OK", null)
                .create()
                .show();
break;

However, the recommended way is to use the showDialog(int) method:

case Activity.RESULT_OK:
    showDialog(YOUR_DIALOG_ID);
break;

Then, override the onCreateDialog method:

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
        case YOUR_DIALOG_ID:
            return new AlertDialog.Builder(this)
                .setMessage("Message")
                .setPositiveButton("OK", null)
                .create();
    }
    return super.onCreateDialog(id);
}

YOUR_DIALOG_ID is just an integer constant. Why is this recommended? glad you asked. If you do it that way, Android will know that you are showing the dialog when it recreates the activity (for instance, when user changes orientation of the device), thus it will be recreated (which does not happen when you show it manually (unless you handle the configuration changes your self (which I think you are not doing (nor more parenthesis)))).


As long as your code returns to UI manager, its ok to do that Dialog. Remember that is not your code that actualy draw Dialogs and Toasts, that happens only outside your code, when your return from your method to UI manager.

Here is an example of what you should and shouldn't do:

//in response of an OnClick method

public void onClick(View v) {
  switch(v.getId())
  {
   case MYBUTTON1ID:
   {
      // show my alert here whatever method
      MyShowAlert("Something wrong..  hit OK to continue");
      DoSomethingMore(); // <<  this is WRONG!!, would happen BEFORE your alertdialog
      DoSomethingEvenMore(); // << wrong either
      break;
   }

   case MYBUTTONID2:
   {
     DoSomething(); // << ok here
     MyShowAlert("Ok, this would work");
     break; // << here we return to UI showing alert
   } 
 }

}

If you need to do that pattern shown in MYBUTTON1ID, you better learn AsyncTask, take a reading here

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜