在运行时以编程方式选择样式/主题 [英] Choosing a style / theme programmatically at run time

查看:80
本文介绍了在运行时以编程方式选择样式/主题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有设备A和设备B.

我可以轻松检测该应用程序是在设备A上还是在设备B上运行.现在我需要在设备A和其他设备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.

我该怎么做?

推荐答案

在Activity.onCreate()中,可以调用setTheme()来设置要使用的主题.请注意,必须在 调用setContentView()之前完成此操作,否则必须创建UI.

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.

请记住,当用户启动您的应用程序时,系统会在发生这种情况时显示它的预览.前面的内容基于创建与清单中声明的​​主题匹配的窗口的基础.您希望它与您将在onCreate()中设置的主题尽可能地匹配,以使向应用程序的过渡尽可能顺利.

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

-v11允许您使用在新平台上运行时使用新主题的主题版本,同时还原到旧版本上兼容的主题.例如,在values-v11样式中,主题的父级可以是新的@android:style/Theme.Holo,而基本主题将从旧的@android:style/Theme继承.

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.

Android 3.0还向您提供一种在运行时更改主题的方法,方法是要求您重新启动活动(如发生配置更改时一样):

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()

在调用之后,所创建的Activity的新实例可以调用setTheme(),其值与先前使用的主题不同(例如,基于保存的实例状态或共享首选项中的信息).

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.

这篇关于在运行时以编程方式选择样式/主题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆