Search code examples
androidandroid-layoutxml-drawablelayer-list

How to make an rectangle with top and bottom shadow in android using layer-list?


This is what i want

I need an yellow rectangle with shadows on top and bottom as given in the image , how can i draw this using layer-list, i have no idea how to do this , especially the shadows how to achieve that shape?


Solution

  • Using a layer-list seems like the best option. You'll need two rectangles, the main yellow one, and another for the shadow. You can then rotate the shadow rectangle a little to get the effect you want.

    For example:

    <?xml version="1.0" encoding="utf-8"?>
    <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:top="20dp" android:left="20dp" android:bottom="20dp" android:right="20dp">
            <rotate
                android:fromDegrees="-5"
                android:toDegrees="-5"
                android:pivotX="50%"
                android:pivotY="50%">
                <shape android:shape="rectangle">
                    <size android:width="300dp"
                        android:height="150dp"/>
                    <solid android:color="#999999"/>
                </shape>
            </rotate>
        </item>
    
        <item android:top="20dp" android:left="20dp" android:bottom="20dp" android:right="20dp">
            <shape android:shape="rectangle">
                <size android:width="300dp"
                    android:height="150dp"/>
                <solid android:color="#FFDD66"/>
            </shape>
        </item>
    </layer-list>
    

    If you need to make the shadow smaller, as you said in a comment, you can scale down the rectangle. You can do this either by making it smaller to begin with (the width and height) or using <scale> ... </scale> tags. Here's a related SO question.