Android : stroke in a shape create a margin of the stroke width
Surround your shape
with <item>...</item>
tags and set up top
, bottom
, left
and right
attributes of <item>
with margin values you want. Then wrap whole item
with a <layer-list>
. See below:
<?xml version="1.0" encoding="utf-8"?><layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:left="{L-Margin}dp" android:right="{R-Margin}dp" android:bottom="{B-Margin}dp" android:top="{T-Margin}dp"> <!-- Insert your shape here: --> <shape android:shape="..."> ... </shape> </item></layer-list>
If you want padding
(instead of margin
), see Ahmad Aghazadeh answer below.
You can use padding Transparent instead of margin
<?xml version="1.0" encoding="UTF-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/listview_background_shape"> <stroke android:width="8dp" android:color="#0000000" /> <padding android:left="2dp" android:top="2dp" android:right="2dp" android:bottom="2dp" /> <solid android:color="@color/white" /></shape>
I had same problem and solved it like this:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item> <shape android:shape="rectangle"> <solid android:color="@color/background" /> <corners android:radius="2dp"/> <stroke android:width="4dp" android:color="@android:color/black" /> </shape> </item> <item> <shape android:shape="rectangle"> <corners android:radius="2dp"/> <solid android:color="@android:color/transparent" /> <stroke android:width="2dp" android:color="@color/background" /> </shape> </item></layer-list>
It gives two drawables with two strokes. First drawable have stroke with width (width + margin of desirable stroke). Second drawable have only visible stroke with width of desirable margin.