Robin
Robin

Reputation: 516

What is the efficient & structured way to use android drawable shape?

I need to use few buttons in my project with different design. So I'm using drawable shape to make custom button.

Let's say I need a button with rounded corner and green background. So I've created a shape "gree_round_button.xml" and this works fine. But then again I need another button with same style just background color would be different, for that do I must need to create another xml file like "colorName_round_button.xml"?

I'm keeping it simple for understanding purpose but there could be many common style for different button may be just one or two property different. Is there any way that I can skip creating multiple files for same design? Is there any way that I can use to extend any shape and may be pass color,background color as a parameter? May be like this "button.xml" this shape will accept one parameter for color and I can use this shape for every button I want to use and just pass the different color as a parameter.

In Web Css: I can do something like this

.button {border: 1px solid #ddd;border-radius:5px;padding:20px;}
.button.green {background:green;}

Is there any easy way to do something like this. Thanks.

Upvotes: 0

Views: 98

Answers (1)

atwrk
atwrk

Reputation: 234

You should take a look at backgroundTint This will allow you to use the same drawable but overlay it with different Colours.

So for instance you could have a bg_circle.xml which is a white circle. Then use tint to change it's color, and have your separate icon as the src.

<ImageButton
    android:layout_width="75dp"
    android:layout_height="75dp"
    android:src="@drawable/ic_check_mark"
    android:background="@drawable/bg_circle"
    android:backgroundTint="@color/red"
    />

This way you only need to have one round_button.xml which you can use as a background to all your buttons, and tint it with different colours as needed. The content of each icon can then be its own drawable.

The four buttons below were made with only 3 drawables:

enter image description here

<ImageButton
    android:layout_width="75dp"
    android:layout_height="75dp"
    android:src="@drawable/ic_feather"
    android:background="@android:drawable/btn_default"
    />

<ImageButton
    android:layout_width="75dp"
    android:layout_height="75dp"
    android:src="@drawable/ic_feather"
    android:background="@android:drawable/btn_default"
    android:backgroundTint="@color/colorPrimaryDark"
    />

<ImageButton
    android:layout_width="75dp"
    android:layout_height="75dp"
    android:src="@drawable/ic_plane"
    android:background="@android:drawable/btn_default"
    android:backgroundTint="@color/colorPrimaryDark"
    />
<ImageButton
    android:layout_width="75dp"
    android:layout_height="75dp"
    android:src="@drawable/ic_plane"
    android:background="@android:drawable/btn_default"
    android:backgroundTint="@color/colorAccent"
    />

Upvotes: 2

Related Questions