开发者

Show dialogue outside of activity

I am try开发者_Python百科ing to launch a dialogue from a non activity java class. Can this be done if so how?


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.


i think this might be useful. You can make a static reference to it.

public class AddDecisionActivity extends Activity{

public static AddDecisionActivity addDecAct;

@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);

    setContentView(R.layout.layout_register_decision);
    addDecAct = AddDecisionActivity.this;
}

public static AddDecisionActivity getAddDecAct(){
    return addDecAct;
}
}

Then you can make further reference to it, and be able to create the alert dialog or whatever you could need.

private void showCloseConfirmationAlert(String message, final String action){
    AlertDialog.Builder alertBuilder = new AlertDialog.Builder(***AddDecisionActivity.getAddDecAct()***);
    alertBuilder.setTitle(R.string.alert_title);
    alertBuilder.setMessage(message);
    alertBuilder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
        }
    });
    alertBuilder.setPositiveButton(R.string.si, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            if(action.equals("logout")){
                Intent cerrarS = new Intent(AddDecisionActivity.getAddDecAct(), LoginActivity.class);
                startActivity(cerrarS);
                finish();
            }
            if(action.equals("finish")){
                finish();
            }

        }
    });

    AlertDialog ad = alertBuilder.create();
    ad.show();
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜