Search code examples
androidxmlkotlinview

How to set color for drawable background in android


I want to create a view like this in android studio https://i.sstatic.net/BTm5P.png

As you can see, three views are using the same background but with different colors. I wonder how to create a view like this with only one drawable background file. Three views are using the same drawable background file, and I can set a different color for each view.


Solution

  • You can use android:backgroundTint for this purpose.

    For example:

    1. Define rounded drawable (ex: rounded.xml)
    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
        <corners android:radius="10dp" />
    </shape>
    
    1. Set your color with backgroundTint
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:backgroundTint="@color/black"
        android:background="@drawable/rounded"/>