hasan_y_shaikh hasan_y_shaikh - 1 month ago 7
Android Question

How to change the color of drawable shape in the layout file

I have created a drawable circular shape. I am using this as a background to my linear layout. It is working fine. But the problem is, I want to create 6 circles with different colors. So can i use only one drawable shape and change its color for different circles?

This is my drawable circular shape

<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval"
>

<solid
android:color="@color/colorPrimary"
/>
<size
android:width="30dp"
android:height="30dp"/>
</shape>


I want to create this layout using drawable circular shape with different colors.

layout:
enter image description here

Answer

You can by setting the same drawable (the one you provided) to all the buttons, then in your code:

Example:

Drawable mDrawable = ContextCompat.getDrawable(context, R.drawable.yourDrawable); 
mDrawable.setColorFilter(new PorterDuffColorFilter(yourColorInt,PorterDuff.Mode.MULTIPLY));

final int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
    yourButton.setBackgroundDrawable(mDrawable);
} else {
    yourButton.setBackground(mDrawable);
}

Do this for each of your buttons, but remember to replace yourColorInt with the color you want for the button you're applying it to.