In some rare scenarios, mobile app developers prefer to set a background color for text in their apps. Let’s learn how to add Text with a custom background color in Jetpack Compose.
The TextStyle helps to set a custom background color to the Text composable. See the code snippet given below.
@Composable
fun TextExample() {
Text(
style = TextStyle(background = Color.Yellow),
text = "This is a sample text. This is an example of adding background color to the text.",
fontSize = 24.sp)
}
The output is given below.

Following is the complete code for reference.
package com.example.myapplication
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
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.text.TextStyle
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(
style = TextStyle(background = Color.Yellow),
text = "This is a sample text. This is an example of adding background color to the text.",
fontSize = 24.sp)
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
MyApplicationTheme {
TextExample()
}
}
I hope this Jetpack Compose Text background color tutorial is helpful for you.