Multiple Themes in one App

suggest change

An application can use more than one theme, and each theme can define its own colors:

First, we have to add our themes to style.xml like this:

<style name="OneTheme" parent="Theme.AppCompat.Light.DarkActionBar">

</style>

<!--  -->
<style name="TwoTheme" parent="Theme.AppCompat.Light.DarkActionBar" >

</style>
......

Above you can see OneTheme and TwoTheme.

Now, go to your AndroidManifest.xml and add this line: android:theme="@style/OneTheme" to your application tag, this will make OneTheme the default theme:

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

Create a new XML file named attrs.xml and add this code:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="custom_red" format="color" />
    <attr name="custom_blue" format="color" />
    <attr name="custom_green" format="color" />
</resources>
<!-- add every color you need (just the color's name) -->

Go back to style.xml and add these colors, with their values, for each theme:

<style name="OneTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="custom_red">#8b030c</item>
    <item name="custom_blue">#0f1b8b</item>
    <item name="custom_green">#1c7806</item>
</style>

<style name="TwoTheme" parent="Theme.AppCompat.Light.DarkActionBar" >
    <item name="custom_red">#ff606b</item>
    <item name="custom_blue">#99cfff</item>
    <item name="custom_green">#62e642</item>
</style>

Now you have custom colors for each theme. Let's add these colors to the views.

Add custom_blue to the TextView with ?attr/:

<TextView
    android:id="@+id/text_view"
    android:textColor="?attr/custom_blue" />

Now change the theme with one line, setTheme(R.style.TwoTheme). That line must run before setContentView() in onCreate():

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTheme(R.style.TwoTheme);
    setContentView(R.layout.main_activity);
    ....
}


Change the theme for all activities at once

To change the theme for every activity, create a MyActivity class that extends AppCompatActivity (or Activity) and call setTheme from onCreate. MySettings is not defined on this page. Each subclass must call super.onCreate() before setContentView():

public class MyActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (new MySettings(this).isDarkTheme())
            setTheme(R.style.TwoTheme);
    }
}

Finally, make every activity extend the MyActivity base class:

public class MainActivity extends MyActivity {
    ....
}

To use another theme, change the setTheme call. This sample uses R.style.TwoTheme when isDarkTheme() is true. R.style.OneTheme and R.style.ThreeTheme are other theme names you can call instead.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents