How to add Text with Border in Android Jetpack Compose

By Mohammed Rashid •  November 21st, 2022 • 

Borders can make UI elements beautiful. Let’s learn how to add Borders to text in Jetpack Compose.

Text composable has many useful parameters. In this case, the Modifier comes in handy. You can show borders using BorderStroke. See the code snippet given below.

@Composable
fun TextExample() {
    Text( modifier = Modifier.border(BorderStroke(2.dp, Color.Red)),
        text = "This is a sample text. This is an example of adding border to text.",
        fontSize = 24.sp)
}

The output is given below.

Following is the complete code.

package com.example.myapplication

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.myapplication.ui.theme.MyApplicationTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyApplicationTheme {
                Surface(
                    color = MaterialTheme.colors.background,
                    modifier = Modifier.padding(20.dp)
                ) {
                    TextExample()
                }
            }
        }
    }
}

@Composable
fun TextExample() {
    Text( modifier = Modifier.border(BorderStroke(2.dp, Color.Red)),
        text = "This is a sample text. This is an example of adding border to text.",
        fontSize = 24.sp)
}

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    MyApplicationTheme {
        TextExample()
    }
}

If you want more control over the border then it is better to use UI elements such as Card.

Keep Reading