How to Support Multiple Themes on Android?

Viewed 28

I have already implemented the dark and light theme:

theme.xml

<style name="Theme.MyApp" parent="Theme.MaterialComponents.DayNight.NoActionBar">
  <item name="colorPrimary">@color/my_app_primary</item>
  <!-- ... -->
</style>

And then I override the color file for each theme:

values/colors.xml

<resources>
    <color name="my_app_primary">@color/red</color>
    <color name="red">#ff0000</color>
    <color name="green">#00ff00</color>
    <!-- .... -->
</resources>

values-night/colors.xml

<resources>
    <color name="my_app_primary">@color/green</color>
    <!-- .... -->
</resources>

I use this code to choose the theme:

int theme = mPreferences.getTheme();
if (theme == ConstUtil.DARK) {
    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
} else if (theme == ConstUtil.LIGHT){
    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
} else {
    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
}

Question: How can I add another theme (third theme) ?

1 Answers

A good idea is : sue your own widget but android widget; such as:

class MyTextView : android.view.TextView; class MyImageView: android.view.ImageView; ....

when you want change any theme or color, only need change the your views background or foreground.

Related