Choosing a style / theme programmatically at run time

安稳与你 提交于 2019-12-20 01:35:41

问题


I have device A and device B.

I can easily detect if the app is running on device A or on device B. Now what I need is to use on theme (styles) for device A and other on device B.

How can I do this?


回答1:


In your Activity.onCreate(), you can call setTheme() to set the theme you would like to use. Note this must be done before you call setContentView() or otherwise create your UI.

Keep in mind that when the user launches your app, the system will show a preview of it while this happen. This previous is based on creating a window that matches the theme declared in your manifest. You want this to match as closely as possible the themes you are going to set in your onCreate() to make the transition to your app as smooth as possible.

If you want your theme to vary based on some device configuration -- such as platform version or screen size -- you can do this all through resources. Just declare different versions of your theme for the different configurations you want. The file layout would be something like:

values/
    styles.xml   # Required default theme
values-v11/
    styles.xml   # Theme when running on Android 3.0 or higher
values-xlarge/
    styles.xml   # Theme when running on an xlarge screen

The -v11 allows you to have a version of the theme that uses a new theme when running on newer platforms while reverting to something compatible on older versions. For example in the values-v11 style your theme's parent could be the new @android:style/Theme.Holo, while the basic one would inherit from the older @android:style/Theme.

Also Android 3.0 gives you a way to change your theme at runtime, by asking that your activity being restarted like when a configuration change happens: http://developer.android.com/reference/android/app/Activity.html#recreate()

After calling that, the new instance of the Activity that gets created can call setTheme() with a different value (based for example on information in the saved instance state or a shared preference) than the theme that was previously being used.



来源:https://stackoverflow.com/questions/6861887/choosing-a-style-theme-programmatically-at-run-time

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