Introduction
In this tutorial, we'll explore how to use the BadgeBox
component in Jetpack Compose, Android’s modern UI toolkit. BadgeBox
allows developers to display notification badges alongside icons or other UI elements, making it a useful tool for showcasing updates or alerts directly within the app interface. In this example, we’ll build a simple app that displays a badge with a favorite icon. The badge will increment whenever a button is pressed, making it an interactive way to learn about badge usage in Jetpack Compose.
This guide is intended for developers with a basic understanding of Kotlin and Jetpack Compose. By following along, you’ll learn how to structure a composable UI, utilize state management, and apply essential Jetpack Compose components like Scaffold
, TopAppBar
, and BadgeBox
to create dynamic and responsive layouts. Let’s dive into the code and break it down step by step.
Main Code Structure in MainActivity
The primary file, MainActivity.kt
, begins by setting up a typical Android AppCompatActivity
. Within this MainActivity
class, the onCreate
method calls the setContent
function, which is a common Jetpack Compose practice. setContent
allows us to define the UI for the activity using composable functions. Here, it calls the GetScaffold
composable function, which is the starting point of the UI structure in this example.
The @ExperimentalMaterialApi
annotation applied here indicates that some of the components or functions, such as BadgeBox
, are part of an experimental API in Jetpack Compose. This is essential to remember, as experimental APIs may change in future releases. In this case, it’s used on the GetScaffold
function, as well as other functions that rely on BadgeBox
.
GetScaffold Function and State Management
The GetScaffold
composable function is where the UI’s core structure is created using a Scaffold
component. Scaffold
is a Jetpack Compose component that provides a basic structure, allowing easy setup for app bars, floating action buttons, drawers, and more. It takes three main parameters here:
topBar
: This parameter is set to aTopAppBarContent
composable function, which defines the top app bar.content
: This parameter is set toMainContent
, the central part of the UI that includes the button to increment the badge counter.backgroundColor
: This sets a specific background color for the overall scaffold layout.
The favCounter
state variable, defined with remember
and mutableStateOf
, keeps track of the badge count. This MutableState
object allows Compose to automatically update the UI whenever the counter changes, making it an essential part of this interactive setup.
TopAppBarContent and BadgeBox
The TopAppBarContent
composable function defines the app’s top bar. Inside this function, TopAppBar
is used to create a typical material design app bar with a title and action items. The title text “Compose - BadgeBox” is set, and a custom background color is applied.
The BadgeBox
component is used to display a badge on the favorite icon, with the badgeContent
parameter displaying the current value of favCounter
. Within BadgeBox
, an Icon
component is used to show the favorite icon, with a contentDescription
to improve accessibility. This setup allows the badge to dynamically display the counter value as it updates, providing real-time feedback on user interaction.
MainContent Function and the Update Button
The MainContent
composable function defines the main content area of the screen, centering a button that increments the badge count. A Box
component, with modifiers to fill the entire screen size and center its contents, contains a Button
that, when clicked, increments the favCounter
state variable by 1.
Inside the Button
component, the Text
component is used to display the label “Update Badge.” This simple user interface makes it easy to see the interaction between the button and the badge count, demonstrating how state changes in Compose propagate throughout the UI.
Preview and Testing with ComposablePreview
At the end of MainActivity.kt
, there’s a ComposablePreview
function annotated with @Preview
. Although it currently comments out the GetScaffold
function, this setup allows for previewing the composable UI in the Android Studio design editor. @Preview
functions are helpful for visualizing and testing UI components without running the entire app on an emulator or device.
Summary
This example demonstrates how to use Jetpack Compose to create a simple yet dynamic UI with BadgeBox
to display a badge counter. By structuring the layout with Scaffold
, incorporating a top app bar with TopAppBar
, and using MutableState
for real-time updates, the code showcases how composable functions work together to build an interactive interface.
With BadgeBox
, you can add badges to icons or other UI elements to signify new information or updates, creating a polished user experience. As Jetpack Compose evolves, components like BadgeBox
will become even more essential for creating responsive, modern Android interfaces.
package com.cfsuman.jetpackcompose
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
class MainActivity : AppCompatActivity() {
@ExperimentalMaterialApi
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
GetScaffold()
}
}
@ExperimentalMaterialApi
@Composable
fun GetScaffold(){
var favCounter = remember {mutableStateOf(1)}
Scaffold(
topBar = { TopAppBarContent(favCounter) },
content = {MainContent(favCounter)},
backgroundColor = Color(0xFFEDEAE0)
)
}
@ExperimentalMaterialApi
@Composable
fun TopAppBarContent(favCounter: MutableState<Int>) {
TopAppBar(
title = { Text(text = "Compose - BadgeBox")},
backgroundColor = Color(0xFFC0E8D5),
actions = {
BadgeBox(
badgeContent = {
Text("${favCounter.value}")
}
) {
Icon(
Icons.Filled.Favorite,
contentDescription = "Favorite"
)
}
Spacer(modifier = Modifier.requiredWidth(12.dp))
}
)
}
@Composable
fun MainContent(favCounter: MutableState<Int>){
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
){
Button(
onClick = {
favCounter.value++
}
) {
Text(text ="Update Badge")
}
}
}
@Preview
@Composable
fun ComposablePreview(){
//GetScaffold()
}
}
- jetpack compose - How to use ModalDrawer
- jetpack compose - Update state of another function variable
- jetpack compose - TopAppBar navigation
- jetpack compose - TopAppBar actions
- jetpack compose - Navigation multiple arguments
- jetpack compose - Navigation arguments data type
- jetpack compose - Navigation object argument
- jetpack compose - TabRow custon indicator
- jetpack compose - Get primary language
- jetpack compose - Get screen orientation
- jetpack compose - How to hide system bars
- jetpack compose - Detect screen orientation change
- jetpack compose ktor - How to get api data
- jetpack compose - Kotlinx serialization not encode null values
- jetpack compose - Kotlinx serialization encode to string