← All Articles

Android - How To Give One Sided Border To Views

Posted on

Unlike the web, Android world doesn’t have out of box solution to give a border to only one side of the views. But we have a hacky way to do this.

We will give our desired border by applying a gradient on view.

Go ahead and create a drawable resource file and give it a name. In my case, it is called bottom_border.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:angle="90"
        android:centerColor="@android:color/transparent"
        android:endColor="@android:color/transparent"
        android:startColor="@color/colorAccent"
        android:centerY="0.03"/>
</shape>

We need to set start, center and end colors, and the angle value according to the side of the view which we want to give the border to.

android:centerX or android:centerY values determine the thickness.

In the image below, you can see the Android canvas degree values. As you can see, it differs a little bit from our real world geometry.

Android Canvas Degrees

Since I’ve wanted my border to be at the bottom of the view, I set the angle to ‘90’. At this point I can consider that centerY value sets the horizontal position of my center color. Lesser values make the shadow more near to the angle point, and vice versa. In my case, 0.03 means pretty close to the bottom.

And that’s it! The last thing you need to do is to set this resource file as your view’s background drawable.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/bottom_border"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Final result looks like:

android-developmentEnglishandroidviewborder