The following implementation can be used to solve the problem of making safe state changes during the Activity life cycle, in particular, to display dialogs: if the state of an instance has already been saved (for example, due to a configuration change), it will postpone until a renewed one is executed state.
public abstract class XAppCompatActivity extends AppCompatActivity { private String TAG = this.getClass().getSimpleName(); private ActivityRetainFragment retainFragment; private boolean instanceStateSaved; @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState);
Then using a class like this:
public abstract class XAppCompatDialogFragment extends AppCompatDialogFragment { public boolean showRequest(XAppCompatActivity activity, final String tag) { return showRequest(activity, tag, null); } public boolean showRequest(XAppCompatActivity activity, final String tag, final Bundle args) { return activity.post(new XAppCompatActivity.ActivityTask() { @Override public void exec(XAppCompatActivity activity) { if (args!= null) setArguments(args); show(activity.getSupportFragmentManager(), tag); } }); } public boolean dismissRequest() { return dismissRequest(null); } public boolean dismissRequest(final Runnable runnable) {
You can safely display dialog boxes without worrying about the state of the application:
public class TestDialog extends XAppCompatDialogFragment { private final static String TEST_DIALOG = "TEST_DIALOG"; public static void show(XAppCompatActivity activity) { new TestDialog().showRequest(activity, TEST_DIALOG); } public TestDialog() {} @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { return new AlertDialog.Builder(getActivity(), R.style.DialogFragmentTheme ) .setTitle(R.string.title)
and then call TestDialog.show(this) from your XAppCompatActivity .
If you want to create a more general dialog class with parameters, you can save them in the Bundle with arguments in the show() method and get them using getArguments() in onCreateDialog() .
The whole approach may seem a bit complicated, but once you have created two base classes for actions and dialogs, it is pretty easy to use and works great. It can be used for other Fragment operations that can be affected by the same problem.
gicci Mar 20 '17 at 17:17 2017-03-20 17:17
source share