简体   繁体   English

管理Android应用主题的最佳方法

[英]The best way to manage android app themes

In my program I have to do switch application themes programmatically. 在我的程序中,我必须以编程方式切换应用程序主题。 That is, there is an option to switch light and dark themes. 也就是说,有一个选项可以切换浅色和深色主题。 What is the best practice? 最佳做法是什么? Can I create and manage the styles set? 我可以创建和管理样式集吗? For instance, I have this textview and button. 例如,我有这个textview和按钮。

<Button
                android:id="@+id/btn"
                style="@style/BT_list"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/OK" />

            <TextView
                android:id="@+id/tv"
                style="@style/TText"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="@string/msg" />

I have this style: 我有这种风格:

<style name="BT_list">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">30dp</item>
    <item name="android:textColor">@color/green_color</item>
    <item name="android:gravity">center</item>
    <item name="android:paddingLeft">0dp</item>
    <item name="android:paddingRight">0dp</item>
    <item name="android:layout_marginLeft">0dp</item>
    <item name="android:layout_marginRight">0dp</item>
    <item name="android:textSize">15sp</item>
    <item name="android:textStyle">bold</item>
    <item name="android:background">@drawable/grad</item>
</style>


<style name="TText">
    <item name="android:textColor">@color/text_color</item>
    <item name="android:background">@color/white"</item>
</style>

How can I change the values with something like setTheme(); 如何使用setTheme();类的值更改值setTheme(); programmatically for both (maybe more) styles? 以编程方式为这两种(也许更多)样式?

You could create a preference activity that gives the user an option to change the theme. 您可以创建一个首选项活动,使用户可以选择更改主题。 After that, in the OnCreate method of the activity you want to theme, you could use: 之后,在您要主题化的活动的OnCreate方法中,可以使用:

    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(this);
    String userTheme = prefs.getString("theme", "1");
    if (userTheme.equals("1"))
        setTheme(R.style.ThemeDark);
    else if (userTheme.equals("2"))
        setTheme(R.style.ThemeLight);

And in your Styles.xml you could add 在您的Styles.xml您可以添加

    <style name="ThemeDark" parent="Holo.Theme">
        <!-- your changes go here -->
    </style>
   <style name="ThemeLight" parent="Holo.Theme.Light">
        <!-- your changes go here -->
    </style>

NOTE: This is my own method of theme changing used with ABS and HoloEverywhere. 注意:这是我自己的与ABS和HoloEverywhere一起使用的主题更改方法。 This will not work if you don't use these libraries 如果您不使用这些库,则将无法使用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM