Show dialogue outside activities

I am trying to start a dialog from a non activity java class. Can this be done, if so, how?

+6
source share
2 answers

You can show the dialog outside the action, but you will need a reference to the Context object.

This class is not active, 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(); } 

You can then reference this in Activity:

 public void onCreate(Bundle icicle) { super.onCreate(icicle); DialogExample otherClass = new DialogExample(this); otherClass.dialogExample(); } 

This can be convenient if you have utilities for creating similar dialogs that are used in several actions in the application.

+9
source

I think this may be helpful. You can make a static link 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 an additional link to it and be able to create an alert dialog box or whatever you may 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(); } 
-1
source

Source: https://habr.com/ru/post/886338/


All Articles