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

Adding a button with default appearance but changed background color


I have a linear layout where I am programatically adding buttons. I want these buttons to have the default appearance and behaviour (floating, shadow etc) of a button except that I want to change the main color.

This is what I've tried

val newContext = ContextThemeWrapper(baseContext, R.style.PrimaryColoredButton)
val button = Button(newContext)
button.text = "test"

my styles.xml contains the following code

<style name="PrimaryColoredButton" parent="Base.Widget.AppCompat.Button.Colored">
    <item name="colorButtonNormal">@color/colorAccent</item>
    <item name="colorControlHighlight">@color/colorPrimary</item>
</style>

However this doesn't change the color of my button but gives the default color.

enter image description here


Solution

  • You can use android:backgroundTint="@android:color/white" but sadly, it just can be used in Android API 21+

    If you want to change the button on Android API level below 21. You can use use AppCompatButton using app namespace instead of android for backgroundTint. So it gonna be like this app:backgroundTint="@android:color/white" .

    For example:

    <android.support.v7.widget.AppCompatButton
    android:id="@+id/my_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="My Button"
    app:backgroundTint="@android:color/white" />