Can I draw rectangle in XML?


I wonder if I can draw rectangle in XML.
I know how to draw using drawRect method programmatically.


Yes you can and here is one I made earlier:

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="" android:id="@+id/listview_background_shape">
    <stroke android:width="2dp" android:color="#ff207d94" />
    <padding android:left="2dp"
        android:bottom="2dp" />
    <corners android:radius="5dp" />
    <solid android:color="#ffffffff" />

You can create a new XML file inside the drawable folder, and add the above code, then save it as rectangle.xml.

To use it inside a layout you would set the android:background attribute to the new drawable shape. The shape we have defined does not have any dimensions, and therefore will take the dimensions of the View that is defined in the layout.

So putting it all together:


Finally; you can set this rectangle to be the background of any View, although for ImageViews you would use android:src. This means you could use the rectangle as the background for ListViews, TextViews…etc.

Answered By – Graham Smith

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published