简体   繁体   中英

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.

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

    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

    <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. This will not work if you don't use these libraries

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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