Search code examples
androidmaterial-designandroid-buttonmaterial-components-androidmaterial-components

Material Components Default to colorAccent instead of colorPrimary


My AppTheme in styles.xml looks like this:

   <style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:textColorPrimary">@color/textColorPrimary</item>
        <item name="android:windowTranslucentStatus">true</item>
        <item name="android:windowTranslucentNavigation">true</item>
    </style>

I set this in Manifest as:

<application
    android:name=".MyApp"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    tools:ignore="GoogleAppIndexingWarning">

According to https://material.io/develop/android/components/ The default color applied to my widgets should be the defined colorPrimary, but mine are picking up colorAccent as the default color. For example, this button:

<com.google.android.material.button.MaterialButton
        android:id="@+id/loginButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="56dp"
        android:layout_marginEnd="56dp"
        android:text="login"
        app:cornerRadius="5dp"
        app:elevation="0dp"
        app:fontFamily="@font/gotham_bold" />

Observed behavior

Expected Behaviour

Am I missing a specific config for this project for this to have button to show colorPrimary and not colorAccent?


Solution

  • Use the Material Components Library 1.1.0 or later.

    The default style of the MaterialButton is:

        <style name="Widget.MaterialComponents.Button" parent="Widget.AppCompat.Button">
            <item name="backgroundTint">@color/mtrl_btn_bg_color_selector</item>
            <!-- .... -->
        </style>
    

    Starting from the version 1.1.0 the @color/mtrl_btn_bg_color_selector is based on the ?attr/colorPrimary:

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
      <item android:color="?attr/colorPrimary" android:state_enabled="true"/>
      <item android:alpha="0.12" android:color="?attr/colorOnSurface"/>
    </selector>
    

    In the version 1.0.0 the selector was based on ?attr/colorAccent:

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
      <item android:color="?attr/colorAccent" android:state_enabled="true"/>
      <item android:color="@color/mtrl_btn_bg_color_disabled"/>
    </selector>