Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Drawable with partial fill

I'd like to use a custom drawable to give my button rounded corners. However, I'd also like the bottom 1/4 of the rectangle to be filled with a particular color. Is this possible? How can I just fill the bottom quarter?

like image 467
Wise Shepherd Avatar asked Sep 16 '25 13:09

Wise Shepherd


1 Answers

Yes, it is possible if you use a Layer List and define overlapping items. Here's an example...

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:top="0dp" android:left="0dp" android:bottom="0dp" android:right="0dp">
        <shape android:shape="rectangle">
            <corner android:radius="5"/>
            <solid android:color="#f000"/>
            <size android:width="200dp"
                android:height="30dp"/>
        </shape>
    </item>

    <item android:top="0dp" android:left="0dp" android:bottom="0dp" android:right="0dp">
        <shape android:shape="rectangle">
            <corner android:radius="5"/>
            <solid android:color="#0f0"/>
            <size android:width="50dp"
                android:height="30dp"/>
        </shape>
    </item>
</layer-list>

You might need to play around with these values and adjust them to your needs

Edit

I don't think you can specify relative values, as in percentage. However, if these values differ based on screen sizes you can (and I recommend) moving this values to a dimension resource file as below...

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="button_full_width">200dp</dimen>
    <dimen name="button_quarter_width">50dp</dimen>
    <dimen name="button_height">30dp</dimen>
</resources>

then specify these dimensions in your drawables as below...

...
<size android:width="@dimen/button_full_width"
                android:height="@dimen/button_height"/>
...

Now, to specify different values for different screen sizes you need to specify resource qualifiers that target different sizes by adding different "values" resource folders and placing the dimension files inside them with different values. The Android system will pick up and load the necessary dimensions at run time based on the device screen size...

res/
    values/
            dimens.xml
    values-small/
            dimens.xml
    values-normal/
            dimens.xml
    values-large/
            dimens.xml
    values-xlarge/
            dimens.xml

for more information check out the documentation

like image 119
Leo Avatar answered Sep 19 '25 05:09

Leo