How to Put a Border Around an Android TextView

How to Put a Border Around an Android TextView

6 June 2024 Stephan Petzl Leave a comment Tech-Help

Adding a border around a TextView in Android can enhance the UI by making the text stand out. There are multiple approaches to achieve this, ranging from using XML drawables to programmatic methods. Below, we explore some of the most effective methods.

Using a Shape Drawable

One of the simplest ways to add a border is by using a shape drawable. This method involves defining a rectangle shape in an XML file and setting it as the background of your TextView.

Step-by-Step Guide

  1. Create a new XML file in the res/drawable folder. Name it back.xml.
  2. Add the following code to define a rectangle shape with a border:
<shape xmlns:android="" android:shape="rectangle" >
   <solid android:color="@android:color/white" />
   <stroke android:width="1dip" android:color="#4fa5d5"/>
  1. Set this drawable as the background of your TextView:
    android:text="Some text"

This approach allows you to customize the border’s color and width easily. You can also use @android:color/transparent for the solid color to have a transparent background.

Alternative Methods

Using a Layer List

A layer list can be used to create more complex borders. You can stack multiple shapes to create various effects.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="">
        <shape android:shape="rectangle">
            <solid android:color="@color/border_color" />
    <item android:top="2dp">
        <shape android:shape="rectangle">
            <solid android:color="@color/background_color" />

Apply this layer list as the background of your TextView in the same way as shown above.

Using a 9-Patch Image

A 9-patch image is another way to add a border. Create a stretchable image with the desired border and set it as the background.

Programmatic Approach

If you prefer a programmatic approach, you can use the GradientDrawable class.

GradientDrawable border = new GradientDrawable();
border.setStroke(1, Color.BLACK);


Choosing the right method depends on your specific needs and the complexity of the border you want to create. For most use cases, using a shape drawable is sufficient and easy to implement.

For mobile developers looking to streamline their testing process, consider using Repeato, a no-code test automation tool for iOS and Android. Repeato allows you to create, run, and maintain automated tests effortlessly, enabling developers to focus on crafting excellent apps. Its computer vision and AI-based approach make it particularly fast and efficient, and it allows non-technical team members to contribute to the testing process.

Like this article? there’s more where that came from!