Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 315
hasan_shaikh Avatar asked Oct 22 '16 05:10

hasan_shaikh


People also ask

How do I change the color of a drawable in XML?

Use app:drawableTint="@color/yourColor" in the xml instade android:drawableTint="@color/yourColor" .

How do you set a layout to a color code?

There are situations when you may want to change the background color of a layout using java code in your Activity. java file, then you can do it by using setBackgroundColor() method on your layout. To your Parent View Layout add an attribute @id/id_name and map it to a variable in your java file.


2 Answers

You can use now backgroundTint tag for changing drawable shape color (API level 21)

                android:backgroundTint="@color/yellow_color"
like image 59
Aditya Rohilla Avatar answered Sep 29 '22 01:09

Aditya Rohilla


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.

like image 38
Ali Bdeir Avatar answered Sep 29 '22 02:09

Ali Bdeir