Simplest yes/no dialog fragment - android

I'd like to make a dialog fragment that asks "Are you sure?" with a "yes/no" reply.
I've looked at the documentation and it's really verbose, going all over the place, explaining how to make advanced dialog boxes, but no intact code on making a simple 'hello world' kind of dialog box. Most tutorials utilize the deprecated dialog box system. The official blog seems to be unnecessarily complicated and difficult to understand.
So, what's the simplest way to create and display a really basic Alert Dialog? Bonus points if it's using the support library.

A DialogFragment is really just a fragment that wraps a dialog. You can put any kind of dialog in there by creating and returning the dialog in the onCreateDialog() method of the DialogFragment.
Heres an example DialogFragment:
class MyDialogFragment extends DialogFragment{
Context mContext;
public MyDialogFragment() {
mContext = getActivity();
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext);
alertDialogBuilder.setTitle("Really?");
alertDialogBuilder.setMessage("Are you sure?");
//null should be your on click listener
alertDialogBuilder.setPositiveButton("OK", null);
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return alertDialogBuilder.create();
}
}
To create the dialog call:
new MyDialogFragment().show(getFragmentManager(), "MyDialog");
And to dismiss the dialog from somewhere:
((MyDialogFragment)getFragmentManager().findFragmentByTag("MyDialog")).getDialog().dismiss();
All of that code will work perfectly with the support library, by just changing the imports to use the support library classes.

So, what's the simplest way to create and display a really basic Alert
Dialog? Bonus points if it's using the support library.
Simply create a DialogFragment(SDK or support library) and override its onCreateDialog method to return an AlertDialog with the desired text and buttons set on it:
public static class SimpleDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setMessage("Are you sure?")
.setPositiveButton("Ok", null)
.setNegativeButton("No way", null)
.create();
}
}
To do something when the user uses one of the buttons you'll have to provide an instance of a DialogInterface.OnClickListener instead of the null references from my code.

For those coding with Kotlin and Anko, you can now do dialogs in 4 lines of code:
alert("Order", "Do you want to order this item?") {
positiveButton("Yes") { processAnOrder() }
negativeButton("No") { }
}.show()

because of Activity / Fragment lifecycle #athor & #lugsprog approach can fail,
more elegant way is to **get activity context from method onAttach and store it as weak reference ** (&try to avoid non default constructor in DialogFragment!, to pass any argument to dialog use arguments) like this:
public class NotReadyDialogFragment extends DialogFragment {
public static String DIALOG_ARGUMENTS = "not_ready_dialog_fragment_arguments";
private WeakReference<Context> _contextRef;
public NotReadyDialogFragment() {
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
/** example pulling of arguments */
Bundle bundle = getArguments();
if (bundle!=null) {
bundle.get(DIALOG_ARGUMENTS);
}
//
// Caution !!!
// check we can use contex - by call to isAttached
// or by checking stored weak reference value itself is not null
// or stored in context -> example allowCreateDialog()
// - then for example you could throw illegal state exception or return null
//
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(_contextRef.get());
alertDialogBuilder.setMessage("...");
alertDialogBuilder.setNegativeButton("Przerwij", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return alertDialogBuilder.create();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
_contextRef = new WeakReference<Context>(activity);
}
boolean allowCreateDialog() {
return _contextRef !== null
&& _contextRef.get() != null;
}
EDIT:
& if You wanna dismiss dialog then:
try to get it
check if it's exist
check if it's showing
dismiss
something like this :
NotReadyDialogFragment dialog = ((NotReadyDialogFragment) getActivity().getFragmentManager().findFragmentByTag("MyDialogTag"));
if (dialog != null) {
Dialog df = dialog.getDialog();
if (df != null && df.isShowing()) {
df.dismiss();
}
}
EDIT2: & if u wanna set dialog as non cancelable u should change onCreatweDialog return statement like this:
/** convert builder to dialog */
AlertDialog alert = alertDialogBuilder.create();
/** disable cancel outside touch */
alert.setCanceledOnTouchOutside(false);
/** disable cancel on press back button */
setCancelable(false);
return alert;

Related

I need to display a simple AlertDialog within a called class

I'm very new to Android, and have a basic question. I need at certain points to display a user notification in a dialog box, which they can simply acknowledge with the OK button.
I'm using:
myActivity.runOnUiThread(new Runnable() {
public void run() {
AlertDialog alertDialog = new AlertDialog.Builder(myContext).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("My message");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
});
This works well in the Main program, but within a called method it needs the Activity and the Context from the main program. Can anybody tell me how to pass these? getApplicationContext() seems to be acceptable, but I can't figure out how to pass the Activity.
Better still of course would be to get the parent Context and Activity within the method, but I can't get that to work either.
I'd be grateful for any help.
-update 10/07/21
Rahul has given me the solution to the problem I posed: how to pass in the Activity and Context.
The problem is that the dialog still doesn't show.
I found a variation online as follows:
AlertDialog.Builder builder = new AlertDialog.Builder(myContext);
builder.setTitle("Alert")
.setMessage("My message")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
but this doesn't work either.
I'm puzzled that such a common and simple task needs so much code. In the desktop languages I'm used to it can be done in a single line.
So my titled question stands, but can anyone see where the code is faulty?
Many thanks
You can either pass activity to the class when initializing the object or you can pass activity when calling the function.
Case 1 (Recommended)
Pass Activity when calling the function:
MyObj myObj = new MyObj();
myObj.showDialog(myValue, ActivityName.this);
Where function will look like this:
public void showDialog(int myValue, Activity activity){
...
}
Then you can use this activity instance inside the method.
Case 2
Pass Activity when initializing the object:
MyObj myObj = new MyObj(ActivityName.this);
Where Class will look like this:
class MyObj{
private Activity thisActivity;
public MyObj(Activity activity){
thisActivity = Activity;
}
...
}
Then you can use this activity instance.
When you have activity object available you can replace context object with it.

how to pass an onclick handler to a custom dialog class

I'm trying to create a custom class for displaying a Yes/No AlertDialog, but I want to onClick handler to be in the activity that instantiates the custom class. So far, the custom class looks like this:
public class YesNoDialog {
private Context gContext = null;
private DialogInterface.OnClickListener onClickListener;
private AlertDialog alertDialog = null;
public YesNoDialog(Context context,
DialogInterface.OnClickListener listener) {
this.gContext = context;
this.onClickListener = listener;
}
public void ShowDialog() {
AlertDialog.Builder alertDialogBuilder = new
AlertDialog.Builder(this.gContext);
alertDialogBuilder.setTitle("Hello World");
alertDialogBuilder
.setMessage("Are you sure?")
.setCancelable(false)
.setPositiveButton("Yes",this.onClickListener)
.setNegativeButton("No",this.onClickListener);
alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
My thinking was to pass the context and onClick handler to the object in the constructor, then assign the handler to the .setPositive and .setNegative buttons.
I implemented the DialogInterface.OnClickListener in my MainActivity class:
public class MainActivity
extends AppCompatActivity
implements DialogInterface.OnClickListener {
And created the onClick handler in MainActivity that should be called when either the Yes or No buttons are clicked in the dialog.
#Override
public void onClick(DialogInterface dialog, int id) {
Log.d("DIALOG RETURNS ID=", Integer.toString(id));
dialog.dismiss();
}
I'm not sure if I'm on the right track or not, but I got stuck in trying to figure out how I would now pass the onClick handler to the YesNoDialog object. I've tried several variations of this:
YesNoDialog dialog = new YesNoDialog(this, MainActivity.onClick);
With no success (won't compile). I have also tried passing only the context, assuming that maybe that's all I really need for .setPositive and .setNegative button handlers, but that didn't work either...this calls require a DialogInterface.OnClickListener.
It feels like I'm close, but I can't get over the hurdle. Can anyone help me connect the dots?
Create a class (DialogUtils) and add this method in it.
public static void showPopUp(Context context
, String title
, String msg
, String positiveBtnTxt
, String negativeBtnTxt
, DialogInterface.OnClickListener positiveBtnListener
, DialogInterface.OnClickListener negativeBtnListener){
final AlertDialog errorDialog;
AlertDialog.Builder errorDialogBuilder = new AlertDialog.Builder(context, R.style.NativeDialogue);
errorDialogBuilder.setTitle(title);
errorDialogBuilder.setMessage(msg);
errorDialogBuilder.setPositiveButton(positiveBtnTxt, positiveBtnListener);
errorDialogBuilder.setNegativeButton(negativeBtnTxt, negativeBtnListener);
errorDialog = errorDialogBuilder.create();
errorDialog.show();
}
Call the method like this :
DialogUtils.showPopUp(this, "title", "message", "positive btn name", "Negative Btn name", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
"Your action"
}
}, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
"Your action"
}
});
This is described in the official documentation on dialogs in Android. In short, you need to do the following steps:
Create a DialogFragment for your dialog so it is properly restored when the device rotates or changes the configuration in some other way.
Create an interface which will allow you to send the result of the dialog.
Implement this interface in the activity.
Cast the activity to the interface inside the DialogFragment in onAttach and store it in some field. Don't forget to set to null in onDetach.
When a dialog button is clicked, you can call the appropriate interface method, and the activity will get the result.
Alternatively, if you only ever use this dialog with one activity, you may not declare an interface and simply store a reference to the activity.
Hey you can make one method in your MainActivity class. Like below.
public void onClickOnYesButton(int id){
}
Pass the MainActivity reference like below.
public YesNoDialog(MainActivity context) {
this.gContext = context;
}
And call the onClickOnYessButton by using the MainActivity reference!
Job done!

Second dialog is automatically destroyed when created from within a first dialog's OnClickListener

Basically, I have a login screen where users type their email and password to log in. After they have submitted their data, I check if they have confirmed their email address. If not, I display a dialog with a corresponding message. In that dialog I provide them with a neutral button to request a new confirmation email, if they haven't received one yet. If they clicked on that button, I wanna show another dialog with a message that the email has been successfully sent. The problem is that whenever I create and show the second dialog from within the first dialog's OnClickListener, the second dialog is instantiated, but then destroyed immediately. So my question is, why is this happening and how do I implement this kind of functionality so that whatever fragment is being shown will be retained across rotation?
NotVerifiedEmailDialog.java (first dialog):
public class NotVerifiedEmailDialog extends DialogFragment
{
private static final String TAG = "NotVerifiedEmailDialog";
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.email_not_verified)
.setMessage(R.string.email_not_verified_message)
.setPositiveButton(android.R.string.ok, null)
.setNeutralButton(R.string.request_new_email, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialogInterface, int which)
{
EmailSentDialog dialog = new EmailSentDialog();
dialog.show(getChildFragmentManager(), dialog.getMyTag());
}
})
.create();
}
public String getMyTag()
{
return TAG;
}
}
EmailSentDialog.java (second dialog):
public class EmailSentDialog extends DialogFragment
{
private static final String TAG = "EmailSentDialog";
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.success)
.setMessage(R.string.email_sent_message)
.setPositiveButton(android.R.string.ok, null)
.create();
}
public String getMyTag()
{
return TAG;
}
}
Try making the following variable as instance variable. Your dialog object may get destroyed by the previous dialog.
EmailSentDialog dialog;
In case anyone encountered this problem, the solution is to replace getChildFragmentManager() with getParentFragment().getChildFragmentManager(). The former gets a child fragment manager of the first dialog, which is gonna be destroyed, because of the button click (that's why the second dialog is destroyed instantly, because it is tied to the first dialog's child fragment manager), while the latter gets a child fragment manager of the parent fragment (in my case, LoginFragment) and, therefore, is not destroyed immediately.

Show AlertDialog from class instance

I have created a separate message popup class based on an offical Android example but I can't figure out how to launch this dialog from another activity. The popup class is:
public class PopupMessage extends DialogFragment {
String message = "";
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(message)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
In my other class I have created an instance:
import com.mcsapp.PopupMessage;
private PopupMessage popup;
popup = new PopupMessage();
When a button is clicked I want to call this. I have this:
case R.id.chooseLocationButton:
if(editTextLocation.getText().toString().equals("")) {
popup.message = "Test";
popup.getDialog().show();
}
break;
}
I have tried a variety of "popup" commands but all result in a crash. I'm sure it's simply I just can't find the correct code. The "message" parameter sets just fine so the import is working.
Thanks
popup.show(getFragmentManager(), "PopupMsgFragment");
You may want to change getFragmentManager() with getSupportFragmentManager() if you are using support v4 activity.

Prevent dialog dismissal on screen rotation in Android

I am trying to prevent dialogs built with Alert builder from being dismissed when the Activity is restarted.
If I overload the onConfigurationChanged method I can successfully do this and reset the layout to correct orientation but I lose sticky text feature of edittext. So in solving the dialog problem I have created this edittext problem.
If I save the strings from the edittext and reassign them in the onCofiguration change they still seem to default to initial value not what was entered before rotation. Even if I force an invalidate does seem to update them.
I really need to solve either the dialog problem or the edittext problem.
Thanks for the help.
The best way to avoid this problem nowadays is by using a DialogFragment.
Create a new class which extends DialogFragment. Override onCreateDialog and return your old Dialog or an AlertDialog.
Then you can show it with DialogFragment.show(fragmentManager, tag).
Here's an example with a Listener:
public class MyDialogFragment extends DialogFragment {
public interface YesNoListener {
void onYes();
void onNo();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (!(activity instanceof YesNoListener)) {
throw new ClassCastException(activity.toString() + " must implement YesNoListener");
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.dialog_my_title)
.setMessage(R.string.dialog_my_message)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((YesNoListener) getActivity()).onYes();
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((YesNoListener) getActivity()).onNo();
}
})
.create();
}
}
And in the Activity you call:
new MyDialogFragment().show(getSupportFragmentManager(), "tag"); // or getFragmentManager() in API 11+
This answer helps explain these other three questions (and their answers):
Android Best way of avoid Dialogs to dismiss after a device rotation
Android DialogFragment vs Dialog
How can I show a DialogFragment using compatibility package?
// Prevent dialog dismiss when orientation changes
private static void doKeepDialog(Dialog dialog){
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
dialog.getWindow().setAttributes(lp);
}
public static void doLogout(final Context context){
final AlertDialog dialog = new AlertDialog.Builder(context)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.titlelogout)
.setMessage(R.string.logoutconfirm)
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
...
}
})
.setNegativeButton("No", null)
.show();
doKeepDialog(dialog);
}
If you're changing the layout on orientation change I wouldn't put android:configChanges="orientation" in your manifest because you're recreating the views anyway.
Save the current state of your activity (like text entered, shown dialog, data displayed etc.) using these methods:
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
That way the activity goes through onCreate again and afterwards calls the onRestoreInstanceState method where you can set your EditText value again.
If you want to store more complex Objects you can use
#Override
public Object onRetainNonConfigurationInstance() {
}
Here you can store any object and in onCreate you just have to call getLastNonConfigurationInstance(); to get the Object.
Just add android:configChanges="orientation" with your activity
element in AndroidManifest.xml
Example:
<activity
android:name=".YourActivity"
android:configChanges="orientation"
android:label="#string/app_name"></activity>
A very easy approach is to create the dialogs from the method onCreateDialog() (see note below). You show them through showDialog(). This way, Android handles the rotation for you and you do not have to call dismiss() in onPause() to avoid a WindowLeak and then you neither have to restore the dialog. From the docs:
Show a dialog managed by this activity. A call to onCreateDialog(int, Bundle) will be made with the same id the first time this is called for a given id. From thereafter, the dialog will be automatically saved and restored.
See Android docs showDialog() for more info. Hope it helps somebody!
Note: If using AlertDialog.Builder, do not call show() from onCreateDialog(), call create() instead. If using ProgressDialog, just create the object, set the parameters you need and return it. In conclusion, show() inside onCreateDialog() causes problems, just create de Dialog instance and return it. This should work! (I have experienced issues using showDialog() from onCreate() -actually not showing the dialog-, but if you use it in onResume() or in a listener callback it works well).
This question was answered a long time ago.
Yet this is non-hacky and simple solution I use for myself.
I did this helper class for myself, so you can use it in your application too.
Usage is:
PersistentDialogFragment.newInstance(
getBaseContext(),
RC_REQUEST_CODE,
R.string.message_text,
R.string.positive_btn_text,
R.string.negative_btn_text)
.show(getSupportFragmentManager(), PersistentDialogFragment.TAG);
Or
PersistentDialogFragment.newInstance(
getBaseContext(),
RC_EXPLAIN_LOCATION,
"Dialog title",
"Dialog Message",
"Positive Button",
"Negative Button",
false)
.show(getSupportFragmentManager(), PersistentDialogFragment.TAG);
public class ExampleActivity extends Activity implements PersistentDialogListener{
#Override
void onDialogPositiveClicked(int requestCode) {
switch(requestCode) {
case RC_REQUEST_CODE:
break;
}
}
#Override
void onDialogNegativeClicked(int requestCode) {
switch(requestCode) {
case RC_REQUEST_CODE:
break;
}
}
}
Definitely, the best approach is by using DialogFragment.
Here is mine solution of wrapper class that helps to prevent different dialogs from being dismissed within one Fragment (or Activity with small refactoring). Also, it helps to avoid massive code refactoring if for some reasons there are a lot of AlertDialogs scattered among the code with slight differences between them in terms of actions, appearance or something else.
public class DialogWrapper extends DialogFragment {
private static final String ARG_DIALOG_ID = "ARG_DIALOG_ID";
private int mDialogId;
/**
* Display dialog fragment.
* #param invoker The fragment which will serve as {#link AlertDialog} alert dialog provider
* #param dialogId The ID of dialog that should be shown
*/
public static <T extends Fragment & DialogProvider> void show(T invoker, int dialogId) {
Bundle args = new Bundle();
args.putInt(ARG_DIALOG_ID, dialogId);
DialogWrapper dialogWrapper = new DialogWrapper();
dialogWrapper.setArguments(args);
dialogWrapper.setTargetFragment(invoker, 0);
dialogWrapper.show(invoker.getActivity().getSupportFragmentManager(), null);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDialogId = getArguments().getInt(ARG_DIALOG_ID);
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return getDialogProvider().getDialog(mDialogId);
}
private DialogProvider getDialogProvider() {
return (DialogProvider) getTargetFragment();
}
public interface DialogProvider {
Dialog getDialog(int dialogId);
}
}
When it comes to Activity you can invoke getContext() inside onCreateDialog(), cast it to the DialogProvider interface and request a specific dialog by mDialogId. All logic to dealing with a target fragment should be deleted.
Usage from fragment:
public class MainFragment extends Fragment implements DialogWrapper.DialogProvider {
private static final int ID_CONFIRMATION_DIALOG = 0;
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
Button btnHello = (Button) view.findViewById(R.id.btnConfirm);
btnHello.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogWrapper.show(MainFragment.this, ID_CONFIRMATION_DIALOG);
}
});
}
#Override
public Dialog getDialog(int dialogId) {
switch (dialogId) {
case ID_CONFIRMATION_DIALOG:
return createConfirmationDialog(); //Your AlertDialog
default:
throw new IllegalArgumentException("Unknown dialog id: " + dialogId);
}
}
}
You can read the complete article on my blog How to prevent Dialog being dismissed? and play with the source code.
It seems that this is still an issue, even when "doing everything right" and using DialogFragment etc.
There is a thread on Google Issue Tracker which claims that it is due to an old dismiss message being left in the message queue. The provided workaround is quite simple:
#Override
public void onDestroyView() {
/* Bugfix: https://issuetracker.google.com/issues/36929400 */
if (getDialog() != null && getRetainInstance())
getDialog().setDismissMessage(null);
super.onDestroyView();
}
Incredible that this is still needed 7 years after that issue was first reported.
You can combine the Dialog's onSave/onRestore methods with the Activity's onSave/onRestore methods to keep the state of the Dialog.
Note: This method works for those "simple" Dialogs, such as displaying an alert message. It won't reproduce the contents of a WebView embedded in a Dialog. If you really want to prevent a complex dialog from dismissal during rotation, try Chung IW's method.
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
myDialog.onRestoreInstanceState(savedInstanceState.getBundle("DIALOG"));
// Put your codes to retrieve the EditText contents and
// assign them to the EditText here.
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Put your codes to save the EditText contents and put them
// to the outState Bundle here.
outState.putBundle("DIALOG", myDialog.onSaveInstanceState());
}
I had a similar problem: when the screen orientation changed, the dialog's onDismiss listener was called even though the user didn't dismiss the dialog. I was able to work around this by instead using the onCancel listener, which triggered both when the user pressed the back button and when the user touched outside of the dialog.
In case nothing helps, and you need a solution that works, you can go on the safe side, and each time you open a dialog save its basic info to the activity ViewModel (and remove it from this list when you dismiss dialog). This basic info could be dialog type and some id (the information you need in order to open this dialog). This ViewModel is not destroyed during changes of Activity lifecycle. Let's say user opens a dialog to leave a reference to a restaurant. So dialog type would be LeaveReferenceDialog and the id would be the restaurant id. When opening this dialog, you save this information in an Object that you can call DialogInfo, and add this object to the ViewModel of the Activity. This information will allow you to reopen the dialog when the activity onResume() is being called:
// On resume in Activity
override fun onResume() {
super.onResume()
// Restore dialogs that were open before activity went to background
restoreDialogs()
}
Which calls:
fun restoreDialogs() {
mainActivityViewModel.setIsRestoringDialogs(true) // lock list in view model
for (dialogInfo in mainActivityViewModel.openDialogs)
openDialog(dialogInfo)
mainActivityViewModel.setIsRestoringDialogs(false) // open lock
}
When IsRestoringDialogs in ViewModel is set to true, dialog info will not be added to the list in view model, and it's important because we're now restoring dialogs which are already in that list. Otherwise, changing the list while using it would cause an exception. So:
// Create new dialog
override fun openLeaveReferenceDialog(restaurantId: String) {
var dialog = LeaveReferenceDialog()
// Add id to dialog in bundle
val bundle = Bundle()
bundle.putString(Constants.RESTAURANT_ID, restaurantId)
dialog.arguments = bundle
dialog.show(supportFragmentManager, "")
// Add dialog info to list of open dialogs
addOpenDialogInfo(DialogInfo(LEAVE_REFERENCE_DIALOG, restaurantId))
}
Then remove dialog info when dismissing it:
// Dismiss dialog
override fun dismissLeaveReferenceDialog(Dialog dialog, id: String) {
if (dialog?.isAdded()){
dialog.dismiss()
mainActivityViewModel.removeOpenDialog(LEAVE_REFERENCE_DIALOG, id)
}
}
And in the ViewModel of the Activity:
fun addOpenDialogInfo(dialogInfo: DialogInfo){
if (!isRestoringDialogs){
val dialogWasInList = removeOpenDialog(dialogInfo.type, dialogInfo.id)
openDialogs.add(dialogInfo)
}
}
fun removeOpenDialog(type: Int, id: String) {
if (!isRestoringDialogs)
for (dialogInfo in openDialogs)
if (dialogInfo.type == type && dialogInfo.id == id)
openDialogs.remove(dialogInfo)
}
You actually reopen all the dialogs that were open before, in the same order. But how do they retain their information? Each dialog has a ViewModel of its own, which is also not destroyed during the activity lifecycle. So when you open the dialog, you get the ViewModel and init the UI using this ViewModel of the dialog as always.
Yes, I agree with the solution of using DialogFragment given by #Brais Gabin, just want to suggest some changes to the solution given by him.
While defining our custom class that extends DialogFragment, we require some interfaces to manage the actions ultimately by the activity or the fragment that has invoked the dialog. But setting these listener interfaces in the onAttach(Context context) method may sometimes cause ClassCastException that may crash the app.
So to avoid this exception, we can create a method to set the listener interfaces and call just it after creating the object of the dialog fragment.
Here is a sample code that could help you understand more-
AlertRetryDialog.class
public class AlertRetryDialog extends DialogFragment {
public interface Listener{
void onRetry();
}
Listener listener;
public void setListener(Listener listener)
{
this.listener=listener;
}
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
builder.setMessage("Please Check Your Network Connection").setPositiveButton("Retry", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Screen rotation will cause the listener to be null
//Always do a null check of your interface listener before calling its method
if(listener!=null&&listener instanceof HomeFragment)
listener.onRetry();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder.create();
}
}
And in the Activity or in the Fragment you call-
AlertRetryDialog alertRetryDialog = new AlertRetryDialog();
alertRetryDialog.setListener(HomeFragment.this);
alertRetryDialog.show(getFragmentManager(), "tag");
And implement the methods of your listener interface in your Activity or the Fragment-
public class YourActivity or YourFragment implements AlertRetryDialog.Listener{
//here's my listener interface's method
#Override
public void onRetry()
{
//your code for action
}
}
Always make sure that you do a null check of the listener interfaces before calling any of its methods to prevent NullPointerException (Screen rotation will cause the listener interfaces to be null).
Please do let me know if you find this answer helpful. Thank You.
Just use
ConfigurationChanges = Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize
and app will know how to handle rotation and screen size.

Categories

Resources