Implement change black/light theme feature in Andr

2020-06-08 10:50发布

I want to have a "change theme" feature in my app. If I call setTheme() in onCreate(), there is one problem.

The moment after I launch my app, a plain white background appears for a second (because I have set light theme in the manifest). After that, the complete layout of my Activity is displayed - it is either with white or black background, according to user's theme preference.

Is there any way I can change whether white or black background appears after launch?

标签: android
3条回答
forever°为你锁心
2楼-- · 2020-06-08 11:35

If you are adding a theme to the entire program than you could start by doing:

In your manifest you add to your application tag that you are using a theme.

<application android:theme="@style/mythemename">

Then look at Theme XML to make sure that you have what you need declared in the appropriate places.

If it is just for a particular action you could add the activity tag

<activity android:theme="@android:style/Theme.propertyname"> 

You can also, if you want your theme to just change the background color, follow the same pattern with either the activity or application tag (what ever one you are using) and set the item name "colorbackground" to what you want.

You can also use Theme XML and remake what you want in your current theme and call that your custom theme using the method above.

I hope this helps and if not please let me know so I might be able to help better in the future.

查看更多
ゆ 、 Hurt°
3楼-- · 2020-06-08 11:35

Another way would be to have a kind of splash screen which will check for a preference variable for example and then decide whether to use the light or the dark theme. This way you could also use XML layouts.

EDIT: Yet another way is to have the all the layout defining stuff in the onCreate() method and then just trigger the onStart() method when ready.

查看更多
男人必须洒脱
4楼-- · 2020-06-08 11:44

Make sure you call setTheme() in onCreate() BEFORE calling setContentView(). Then if you want to dynamically change the theme again later, you should simply restart your activity.

查看更多
登录 后发表回答