TopAppBar Title Example – Android Jetpack Compose

TopAppBar Title Example

To display title in the TopAppBar, you can use title parameter of the TopAppBar composable.

TopAppBar Title

In this tutorial, we will look into an Android Jetpack Compose example, where we set a title in the TopAppBar.

The following is the code for TopAppBar composable with title parameter set to ‘Sample Title’.

TopAppBar(
    title = {
        Text(
            "Sample Title",
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
    },
)

Example Application for Title in TopAppBar

Create an Android application with Jetpack Compose and Kotlin, and use the following MainActivity.kt code.

MainActivity.kt

package com.example.myapplication

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.example.myapplication.ui.theme.MyApplicationTheme


class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyApplicationTheme {
                ScaffoldExample()
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ScaffoldExample() {
    Scaffold(
        topBar = {
            TopAppBar(
                colors = TopAppBarDefaults.centerAlignedTopAppBarColors(
                    containerColor = MaterialTheme.colorScheme.primaryContainer,
                    titleContentColor = MaterialTheme.colorScheme.primary,
                ),
                title = {
                    Text(
                        "Sample Title",
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                    )
                },
            )
        },
    ) { innerPadding ->
        Column(
            modifier = Modifier
                .padding(innerPadding),
            verticalArrangement = Arrangement.spacedBy(16.dp),
        ) {
            // body
        }
    }
}

Screenshot on Emulator

TopAppBar Title Example - Android Jetpack Compose

Summary

In this tutorial, we have seen how to display center aligned Top Application Bar composable with a title and some actions, in Android Jetpack Compose, using CenterAlignedTopAppBar composable.