Choosing a style / theme programmatically at run time

后端 未结 1 1191
余生分开走
余生分开走 2021-01-20 00:23

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 othe

相关标签:
1条回答
  • 2021-01-20 00:59

    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.

    0 讨论(0)
提交回复
热议问题