Apply an AppCompat theme

Download android eBook

Example

The AppCompat support library provides themes to build apps with the Material Design specification. A theme with a parent of Theme.AppCompat is also required for an Activity to extend AppCompatActivity.

The first step is to customize your theme’s color palette to automatically colorize your app.
In your app's res/styles.xml you can define:

<!-- inherit from the AppCompat theme -->
<style name="AppTheme" parent="Theme.AppCompat">

    <!-- your app branding color for the app bar -->
    <item name="colorPrimary">#2196f3</item>
    
    <!-- darker variant for the status bar and contextual app bars -->
    <item name="colorPrimaryDark">#1976d2</item>

    <!-- theme UI controls like checkboxes and text fields -->
    <item name="colorAccent">#f44336</item>
</style>

Instead of Theme.AppCompat, which has a dark background, you can also use Theme.AppCompat.Light or Theme.AppCompat.Light.DarkActionBar.

You can customize the theme with your own colours. Good choices are in the Material design specification colour chart, and Material Palette. The "500" colours are good choices for primary (blue 500 in this example); choose "700" of the same hue for the dark one; and an a shade from a different hue as the accent colour. The primary colour is used for your app's toolbar and its entry in the overview (recent apps) screen, the darker variant to tint the status bar, and the accent colour to highlight some controls.

After creating this theme, apply it to your app in the AndroidManifest.xml and also apply the theme to any particular activity. This is useful for applying a AppTheme.NoActionBar theme, which lets you implement non-default toolbar configurations.

<application android:theme="@style/AppTheme" 
    ...>
    <activity 
        android:name=".MainActivity"
        android:theme="@style/AppTheme" />
</application>

You can also apply themes to individual Views using android:theme and a ThemeOverlay theme. For example with a Toolbar:

<android.support.v7.widget.Toolbar
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:background="?attr/colorPrimary"
  android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

or a Button:

<Button
    style="@style/Widget.AppCompat.Button.Colored"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:theme="@style/MyButtonTheme"/>

<!-- res/values/themes.xml -->
<style name="MyButtonTheme" parent="ThemeOverlay.AppCompat.Light">
    <item name="colorAccent">@color/my_color</item>
</style>

Stats

Contributors: 5
2017-07-16
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook