1

The background color of the button won't change.

Here is the code:

<?xml version="1.0" encoding="utf-8"?>
 <androidx.constraintlayout.widget.ConstraintLayout 
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   android:background="@color/purple_500">

<Button
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:layout_margin="5dp"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    android:background="@color/white"/>


</androidx.constraintlayout.widget.ConstraintLayout>

This is what the layout and blueprint looks like:

This is what the layout and blueprint looks like

Zoe
  • 27,060
  • 21
  • 118
  • 148

2 Answers2

0

Instead of android:background use app:backgroundTint.

This will make your code look like this:

<?xml version="1.0" encoding="utf-8"?>
 <androidx.constraintlayout.widget.ConstraintLayout 
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   android:background="@color/purple_500">

<Button
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:layout_margin="5dp"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:backgroundTint="@color/white"/>


</androidx.constraintlayout.widget.ConstraintLayout>
user14678216
  • 2,886
  • 2
  • 16
  • 37
0

Another way is ThemeOverlay, you can make a ThemeOverlay like this :

<style name="ThemeOverlay.Button.Red" parent="MaterialButtonStyle">
    <item name="colorOnPrimary">@color/white</item>
    <item name="colorPrimary">@color/red</item>
</style>

and then

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/purple_500">

<com.google.android.material.button.MaterialButton
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:layout_margin="5dp"
    android:theme="@style/ThemeOverlay.Button.Red"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />


</androidx.constraintlayout.widget.ConstraintLayout>

colorPrimary=background of the button

colorOnPrimary= textColor of the button

hamid Mahmoodi
  • 690
  • 4
  • 16