How to draw border on just one side of a linear layout?
Solution 1:
You can use this to get border on one side
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#FF0000" />
</shape>
</item>
<item android:left="5dp">
<shape android:shape="rectangle">
<solid android:color="#000000" />
</shape>
</item>
</layer-list>
EDITED
As many including me wanted to have a one side border with transparent background, I have implemented a BorderDrawable
which could give me borders with different size and color in the same way as we use css. But this could not be used via xml. For supporting XML, I have added a BorderFrameLayout
in which your layout can be wrapped.
See my github for the complete source.
Solution 2:
Easy as pie, allowing a transparent bg:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:angle="0"
android:startColor="#f00"
android:centerColor="@android:color/transparent"
android:centerX="0.01" />
</shape>
Change the angle to change border location:
- 0 = left
- 90 = bottom
- 180 = right
- 270 = top
Solution 3:
it is also possible to implement what you want using a single layer
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:bottom="-5dp"
android:right="-5dp"
android:top="-5dp">
<shape android:shape="rectangle" >
<solid android:color="@color/color_of_the_background" />
<stroke
android:width="5dp"
android:color="@color/color_of_the_border" />
</shape>
</item>
</layer-list>
this way only left border is visible but you can achieve any combination you want by playing with bottom
, left
, right
and top
attributes of the item
element
Solution 4:
To get a border on just one side of a drawable, apply a negative inset
to the other 3 sides (causing those borders to be drawn off-screen).
<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:insetTop="-2dp"
android:insetBottom="-2dp"
android:insetLeft="-2dp">
<shape android:shape="rectangle">
<stroke android:width="2dp" android:color="#FF0000" />
<solid android:color="#000000" />
</shape>
</inset>
This approach is similar to naykah's answer, but without the use of a layer-list
.