Android triangle (arrow) defined as an XML shape

24 08 2013

Arrow icons are widely used in android applications. Some use cases are pagination, incrementing or decrementing numeric values or on next / previous buttons. The example of such arrow that I needed was gray triangle arrow like this one

tr

I decided to build such reusable arrow as an xml drawable, so that there is no need to generate plain graphic .png files each time. Thanks to it I can easily change the colour, size and arrow direction.

Source

I created arrow_up.xml file in drawables directory with contents:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <rotate
            android:fromDegrees="45"
            android:toDegrees="45"
            android:pivotX="-40%"
            android:pivotY="87%" >
            <shape
                android:shape="rectangle" >
                <stroke android:color="@color/transparent" android:width="10dp"/>
                <solid
                    android:color="@color/your_color_here" />
            </shape>
        </rotate>
    </item>
</layer-list>

The idea is to create rectangle shape (<shape/>), fill with gray solid color (<solid/>), rotate it 45 degrees (<rotate/>) and move it over X and Y axis (pivotX and pivotY) in a way that only half of the rectangle is visible (cut along the diagonal).

I also added thick border (<stroke/>) with transparent color. This is because my arrow is a button, so the invisible part around is needed to ease the click (it enlarges click detection area size).

How to use it

The usage is as simple as any other xml drawable shape. It is just enough to set it as view background. Here is button example:

<Button
	android:layout_width="70dp"
	android:layout_height="70dp"
	android:background="@drawable/arrow_up" />

If you need arrow pointing in other direction, you can just rotate it. Here is arrow down:

<Button
	android:layout_width="70dp"
	android:layout_height="70dp"
	android:rotation="180"
	android:background="@drawable/arrow_up" />

So comapred to png icon it is:

scalable, because you can change its size as you wish, without providing bigger or smaller png files for each screen density. And there is no ‘pixelization’ visible regardless of scale used
customizable, because you can easier adjust its color to better fit your UI or use it in other projectno need to regenerate png file and change it in project. Just change the xml attribute.

Quite tricky and nice :)

Did I help you?
I manage this blog and share my knowledge for free sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!

Advertisements







%d bloggers like this: