Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show dialogue outside of activity

Tags:

android

I am trying to launch a dialogue from a non activity java class. Can this be done if so how?

like image 747
user629126 Avatar asked Apr 20 '11 21:04

user629126


1 Answers

You can show a Dialog outside of an activity, but you'll need a reference to a Context object.

This class isn't an activity but can create and show dialogs:

public class DialogExample {
  public Context mContext;

  public DialogExample(Context context) {
    mContext = context;
  }

  public void dialogExample() {
    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
    builder.setMessage("Dialog created in a separate class!");
    builder.show();
  }

Then you can reference this in an Activity:

public void onCreate(Bundle icicle) {
  super.onCreate(icicle);

  DialogExample otherClass = new DialogExample(this);
  otherClass.dialogExample();
}

This can be handy when you have utility methods for creating similar dialogs that are used in multiple activities in an app.

like image 141
tonyc Avatar answered Sep 20 '22 06:09

tonyc