How to Create a TextButton in Jetpack Compose?

Jetpack Compose TextButton

In this article, we will learn how to create a TextButton in Android Jetpack Compose.

Prerequisites:

This article talks about the Material 2 Outlined Button. If you want the latest Material 3 version, follow this link.

First, create an empty Jetpack Compose project and open the MainActivity.kt. Create a MyUI() composable and call it from the onCreate() method.

// add the following imports
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            YourProjectNameTheme(darkTheme = false) {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    Column(
                        modifier = Modifier.fillMaxSize(),
                        verticalArrangement = Arrangement.Center,
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        MyUI()
                    }
                }
            }
        }
    }
}

@Composable
fun MyUI() {
    
}

We will write our code in the MyUI().

Jetpack Compose provides TextButton API. It looks like this:

@Composable
@NonRestartableComposable
fun TextButton(
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
    enabled: Boolean = true,
    interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
    elevation: ButtonElevation? = null,
    shape: Shape = MaterialTheme.shapes.small,
    border: BorderStroke? = null,
    colors: ButtonColors = ButtonDefaults.textButtonColors(),
    contentPadding: PaddingValues = ButtonDefaults.TextButtonContentPadding,
    content: @Composable RowScope.() -> Unit
)

onClick – A lambda that is called when the user clicks on the button.

modifier – It modifies the layout of the button.

enabled – If the button is enabled or not. If it is false, users cannot click on the button.

interactionSource – The MutableInteractionSource for observing the interactions for this button.

elevation – The shadow below the button. A text button typically has no elevation.

shape – It is the shape of the button. We can use any shape API that Jetpack Compose provides.

border – The border around the button.

colors – Button colors.

contentPadding – The spacing between the button’s container and the content.

content – The content of the button, typically a Text().

Let us understand these parameters with use cases.

Simple TextButton Example:

For a simple button, onClick and content are mandatory. In the content, we add text using the Text() composable. The content is a row scope. So, if you add multiple items, they are placed horizontally.

@Composable
fun MyUI() {
    val context = LocalContext.current.applicationContext

    TextButton(
        onClick = {
            Toast.makeText(context, "Click", Toast.LENGTH_SHORT).show()
        }
    ) {
        Text(text = "Click Me")
    }
}

Output:

Simple TextButton Example in Jetpack Compose

TextButton Background Color:

The colors parameter helps us to set the background color. We should call textButtonColors() and pass the required color.

@Composable
fun textButtonColors(
    backgroundColor: Color = Color.Transparent,
    contentColor: Color = MaterialTheme.colors.primary,
    disabledContentColor: Color = MaterialTheme.colors.onSurface
        .copy(alpha = ContentAlpha.disabled)
)

There are different ways to use colors. Here is an article about colors in Jetpack Compose.

@Composable
fun MyUI() {
    val context = LocalContext.current.applicationContext

    TextButton(
        onClick = {
            Toast.makeText(context, "Click", Toast.LENGTH_SHORT).show()
        },
        colors = ButtonDefaults.textButtonColors(
            backgroundColor = Color.Green.copy(alpha = 0.2f)
        )
    ) {
        Text(text = "Click Me")
    }
}

Output:

TextButton Background Color

TextButton Shape and Border:

Jetpack Compose provides RoundedCornerShape API. We can set different shapes using it. To add a border, call the BorderStroke() method.

@Composable
fun MyUI() {
    val context = LocalContext.current.applicationContext

    TextButton(
        onClick = {
            Toast.makeText(context, "Click", Toast.LENGTH_SHORT).show()
        },
        shape = RoundedCornerShape(percent = 15),
        border = BorderStroke(width = 2.dp, color = Color.Green)
    ) {
        Text(text = "Click Me")
    }
}

Output:

TextButton Shape and Border

TextButton Size:

We can change the text button size by using the modifiers like size(), height(), etc.

@Composable
fun MyUI() {
    val context = LocalContext.current.applicationContext

    TextButton(
        modifier = Modifier.size(height = 48.dp, width = 100.dp),
        onClick = {
            Toast.makeText(context, "Click", Toast.LENGTH_SHORT).show()
        },
        colors = ButtonDefaults.textButtonColors(
            backgroundColor = Color.Green.copy(alpha = 0.2f)
        )
    ) {
        Text(text = "Click Me")
    }
}

Output:

TextButton Size

TextButton with Icon:

If you want to include an icon, add Icon() and Text() in the content block. By default, they are arranged horizontally.

@Composable
fun MyUI() {
    val context = LocalContext.current.applicationContext

    TextButton(
        onClick = {
            Toast.makeText(context, "Click", Toast.LENGTH_SHORT).show()
        },
        shape = RoundedCornerShape(percent = 15),
        border = BorderStroke(width = 2.dp, color = Color.Green)
    ) {
        Icon(imageVector = Icons.Default.Add, contentDescription = null)
        Spacer(modifier = Modifier.width(width = 4.dp)) // padding
        Text(text = "Add")
    }
}

Output:

TextButton with Icon

Related: Margin and Padding in Jetpack Compose

TextButton’s Text Style:

The default text style for internal text components is Typography.button. We can change it using the Text() composable‘s parameters like color and size.

@Composable
fun MyUI() {
    val context = LocalContext.current.applicationContext

    TextButton(
        onClick = {
            Toast.makeText(context, "Click", Toast.LENGTH_SHORT).show()
        }
    ) {
        Text(
            text = "Click Me",
            fontSize = 26.sp,
            color = Color.Red
        )
    }
}

Output:

TextButton Text Color and Size

TextButton Elevation:

We can use the elevation parameter to set the shadow below the button. Call the elevation() composable and pass the desired values.

@Composable
fun elevation(
    defaultElevation: Dp = 2.dp,
    pressedElevation: Dp = 8.dp,
    disabledElevation: Dp = 0.dp,
    hoveredElevation: Dp = 4.dp,
    focusedElevation: Dp = 4.dp
): ButtonElevation

Example:

@Composable
fun MyUI() {
    val context = LocalContext.current.applicationContext

    TextButton(
        onClick = {
            Toast.makeText(context, "Click", Toast.LENGTH_SHORT).show()
        },
        colors = ButtonDefaults.textButtonColors(
            backgroundColor = Color.Green.copy(alpha = 0.2f)
        ),
        elevation = ButtonDefaults.elevation(
            defaultElevation = 2.dp,
            pressedElevation = 0.dp
        )
    ) {
        Text(text = "Click Me")
    }
}

Output:

TextButton Elevation

This is all about TextButton in Android Jetpack Compose. I hope you have learned something new. If you have any doubts, comment below.

Related Articles:

References:

Leave a Comment