【问题标题】:Theme change doesn't work on <4.0 as it should主题更改不适用于 <4.0,因为它应该
【发布时间】:2012-09-27 15:54:12
【问题描述】:

我在以编程方式设置“主题切换器”时遇到了一些困难。 我想从应用程序切换主题(在白色(Theme.Light.NoTitleBar)和黑暗(Theme.Black.NoTitleBar)之间),我所做的是: 我设置了一个 SharedPreference:

final String PREFS_NAME = "MyPrefsFile";
    final SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    final SharedPreferences.Editor editor = settings.edit();

比我有两个按钮来切换主题(第二个几乎相同)

Button ThemeWhite = (Button) findViewById(R.id.ThemeWhite);
    ThemeWhite.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            editor.putBoolean("Theme", false);
              editor.commit();
              System.exit(2);
        }
    });

在请求每项活动时,我都会检查 SharedPreference

boolean theme = settings.getBoolean("Theme", false);
    if(theme){
        this.setTheme(R.style.Theme_NoBarBlack);
    } else{
        this.setTheme(R.style.Theme_NoBar);
    }

    setContentView(R.layout.aplikacja);

我在文件夹值中的文件 styles.xml 中定义主题:

<resources>
<style name="Theme.NoBar" parent="@android:style/Theme.Light.NoTitleBar" />
<style name="Theme.NoBarBlack" parent="@android:style/Theme.NoTitleBar" />

在值-v11 中:

<resources>
<style name="Theme.NoBar" parent="@android:style/Theme.Holo.Light.NoActionBar" />
<style name="Theme.NoBarBlack" parent="@android:style/Theme.Holo.NoActionBar" />

在值-v14 中:

<resources>
<style name="Theme.NoBar" parent="@android:style/Theme.DeviceDefault.Light.NoActionBar" />
<style name="Theme.NoBarBlack" parent="@android:style/Theme.DeviceDefault.NoActionBar" />

清单文件:

    <application
...
        android:theme="@style/Theme.NoBar" >

在 android >4.0 上一切都运行良好 但是当我使用 2.2 时它不会改变主题 - 只是字体变白了,但没有深色背景。

我尝试检查它是否至少有效并更改了 Theme.NoBarBlack 的值(对于 android

编辑(发现问题): 因此,在尝试后发现在 Android 2.2 Manifest 文件中设置了背景和休息,并且以编程方式更改主题仅影响文本颜色。知道为什么会这样吗?

回答(因为我没有 10 声望): 在 android 很重要

super.onCreate(savedInstanceState);

是否在设置主题之前。

应该是这样的:

public void onCreate(Bundle savedInstanceState) {
    setTheme(R.style.Theme_NoBar);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.lista);
}

抱歉,伙计们无中生有,但当它在 >3.0 上工作时,我很困惑。花半天时间在上面,但工作。 :)

【问题讨论】:

    标签: android android-layout styles themes android-theme


    【解决方案1】:

    您的styles.xml 中有错误: 对于Theme.NoBarBlack,您将父级设置为@android:style/Theme.NoActionBar,但它不存在。

    我想你的意思是@android:style:Theme.NoTitleBar。

    【讨论】:

    • 谢谢,但我在尝试更改主题等时犯了这个错误,而不是忘记将其更改回来并复制粘贴到这里。所以一定是其他原因导致了这种奇怪的行为。
    • 不错的猜测,但 Theme.NoTitleBar 在该 API 级别不存在。它需要是 Theme.Black.NoTitleBar
    • @StephanBranczyk Android Documentation 表示 Theme.NoTitleBar 从 API 级别 1 开始就存在。
    • 你完全正确。文档中的表格让我感到困惑。
    猜你喜欢
    • 2021-01-28
    • 1970-01-01
    • 2014-07-13
    • 1970-01-01
    • 1970-01-01
    • 2013-12-05
    • 2020-12-24
    • 2018-12-30
    • 2013-10-11
    相关资源
    最近更新 更多