Recreate the backstack in Android

亡梦爱人 提交于 2020-01-14 07:24:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!