How to create Text Button in Android Jetpack Compose

By Mohammed Rashid •  November 19th, 2022 • 

Text buttons are used to create buttons with lesser significance. They are commonly used in cards and dialogs. Let’s learn how to add a text button in Android using Jetpack Compose.

The Text composable can be made clickable with the help of the Modifier. In this example, we are creating a text button with TextButton composable. The TextButton has useful parameters such as onClick, modifier, enabled, elevation, shape, border, colors, etc.

@Composable
fun TextButtonExample() {
    TextButton(onClick = { /* Do something! */ }) {
        Text("Text Button")
    }
}

The TextButton appears as given below.

switch jetpack compose

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.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.tooling.preview.Preview
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,
                ) {
                    TextButtonExample()
                }
            }
        }
    }
}

@Composable
fun TextButtonExample() {
    TextButton(onClick = { /* Do something! */ }) {
        Text("Text Button")
    }
}

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

That’s how you add a text button in Jetpack Compose.

Keep Reading