问题
I have just implemented a way to change the theme in my app. Pressing a button sets a value in SharedPreferences, then the Activity is recreated, and the theme is changed due to the flag.
The problem is how to handle the backstack. Simply recreating the activity is not good because pressing the hardware back button will resume the previous activity (with the old theme still set), whereas if the user did the following:
Start in Activity A > B > C > Press theme change button > Press hardware back button
Then I want them to be taken back to Activity B with the new theme correctly applied. The best solution I've found so far is to recreate the backstack based on the object hierarchy as follows:
Intent intent = new Intent();
intent.setClass(activity, activity.getClass());
TaskStackBuilder stackBuilder = TaskStackBuilder.create(activity);
stackBuilder.addNextIntentWithParentStack(intent);
stackBuilder.startActivities(new Bundle());
However the Activity hierarchy in our app is not well defined (i.e. C can have multiple parents), therefore the code above can lead to the user being taken back to an unexpected activity after pressing the back button.
Is there a clean way to rebuild the back-stack based on the actual back-stack rather than the Activity hierarchy?
来源:https://stackoverflow.com/questions/31197843/recreate-the-backstack-in-android