Change Activity Theme From a Fragment

主宰稳场 提交于 2019-12-06 09:33:47
Lisa Wray

I think I can help you with this. I spent a lot of time over the last few months working on the exact same thing for my app.

The above poster isn't exactly correct. You need to set the theme in onCreate() before views are instantiated -- before setContentView(). When super.onCreate() is called isn't important. I don't see setContentView() in your code above, so I'm wondering if you removed it?

However, if your activity is being themed correctly when you rotate (because it is destroyed and recreated on orientation change) then there's nothing wrong with how you're setting the theme. Instead, I'm inclined to think you're mistaken about onCreate() being called when you exit the SettingsFragment.

You can force your activity to recreate itself like this:

finish();
startActivity(getIntent());

Please first try setting a breakpoint in your activity's onCreate() method and confirm whether it's hit on exiting your fragment (I bet it's not.) Then try the code above.

Call applySetting() before super.onCreate().

If it's not working neither, answer this: when you set your preferences to dark style and close your app completely, when you open your activity, does your style is fine? ( check this with both applySetting() before and after `super.onCreate() )

The problem here is that unless you recreate the activity the theme will not be applied. Themes are applied to an activity prior to setContentView method call in onCreate(). When you navigate back you are not re-entering through the onCreate() method but through onResume().

To work around this issue, changing a theme preference will mean having to clear the back stack, otherwise the theme will not be applied to the activities in the back stack. From a usability point of view this sort of setting should only be available through the top level activities of your app anyway.

Implement a ThemeChangeListener and add it to your activities. When the theme changes, call the ThemeChangeListener and call finish() on any open activities (apart from the page you are in). Then in onBack() manually recreate the top level activity the user navigated to the settings page from using the code Lisa supplied.

You can use intent extras/data to manage re-creating the parent activity with the data previously populated.

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