Android Jetpack

How to create a TopAppBar in Jetpack Compose

Pinterest LinkedIn Tumblr

Hello Devs, If you’re looking to create a modern app, a TopAppBar is a must-have feature. With Jetpack Compose, it’s easy to create a customizable TopAppBar. In this tutorial, we’ll walk you through the steps to create a TopAppBar in Jetpack Compose and elevate your app’s design.

Introduction to TopAppBar in Jetpack Compose

TopAppBar is a material design component that provides a consistent navigation and action bar for your app. With Jetpack Compose. You can easily create a TopAppBar that fits your app’s unique style and functionality. In this tutorial, we’ll cover the basics of creating a TopAppBar in Jetpack Compose, including how to add icons, menus, and custom actions. Let’s get started!

Setting up the TopAppBar layout

To create a TopAppBar in Jetpack Compose, you’ll need to start by setting up the layout. First, create a Scaffold composable function that will hold your TopAppBar and other content.

Inside the Scaffold, add a TopAppBar composable function and pass in the necessary parameters, such as the title and navigation icon.

@Composable
fun CreateScaffold() {
  val scaffoldState = rememberScaffoldState()
  Scaffold(
    topBar = { TopAppBarCompose() }, scaffoldState = scaffoldState
  ) {
    /**
     * Create the Main UI
     */
    MainUi()
  }
}

Create a TopAppBar layout

You can also customize the TopAppBar by adding actions, menus, and other elements. With just a few lines of code, you can create a sleek and functional TopAppBar for your app.

package com.topappbarjetpackcompose

import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource

@Composable
fun TopAppBarCompose() {
  val context = LocalContext.current
  val icon1 = painterResource(id = R.drawable.ic_fav)
  val icon2 = painterResource(id = R.drawable.ic_search)
  val showMenu = remember {
    mutableStateOf(false)
  }

  TopAppBar(contentColor = Color.White, title = { Text(text = "Top app bar") }, navigationIcon = {
    IconButton(onClick = {
      makeToast(context, "TopAppBar menu clicked")
    }) {
      Icon(Icons.Default.Menu, contentDescription = null)
    }
  })
}

Adding icons and actions to the TopAppBar.

One of the great features of the TopAppBar in Jetpack Compose is the ability to add icons and actions. To add an icon, simply use the IconButton composable function and pass in the icon you want to use. .

    actions = {
    IconButton(onClick = { makeToast(context, "Favourites") }) {
      Icon(painter = icon1, contentDescription = null)
    }
    IconButton(onClick = { makeToast(context, "Search") }) {
      Icon(painter = icon2, contentDescription = null)
    }
    IconButton(onClick = { showMenu.value = true }) {
      Icon(Icons.Default.MoreVert, contentDescription = null)
    }
  }

Customizing the TopAppBar with themes and styles.

You can also add actions to the TopAppBar by using the DropdownMenu composable function. This allows you to create a dropdown menu with multiple options that users can select from. With these features, you can create a TopAppBar that not only looks great but also provides useful functionality for your app’s users

You can also use styles to apply custom styling to individual components within the TopAppBar, such as the title or icon. With these customization options, you can create a TopAppBar that perfectly matches your app’s design and branding.

package com.topappbarjetpackcompose

import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource

@Composable
fun TopAppBarCompose() {
  val context = LocalContext.current
  val icon1 = painterResource(id = R.drawable.ic_fav)
  val icon2 = painterResource(id = R.drawable.ic_search)
  val showMenu = remember {
    mutableStateOf(false)
  }

  TopAppBar(contentColor = Color.White, title = { Text(text = "Top app bar") }, navigationIcon = {
    IconButton(onClick = {
      makeToast(context, "TopAppBar menu clicked")
    }) {
      Icon(Icons.Default.Menu, contentDescription = null)
    }
  },
    actions = {
    IconButton(onClick = { makeToast(context, "Favourites") }) {
      Icon(painter = icon1, contentDescription = null)
    }
    IconButton(onClick = { makeToast(context, "Search") }) {
      Icon(painter = icon2, contentDescription = null)
    }
    IconButton(onClick = { showMenu.value = true }) {
      Icon(Icons.Default.MoreVert, contentDescription = null)
    }
    DropdownMenu(expanded = showMenu.value, onDismissRequest = { showMenu.value = false }) {
      DropdownMenuItem(onClick = { makeToast(context, "Settings clicked") }) {
        Text(text = "Settings")
      }
      DropdownMenuItem(onClick = { makeToast(context, "Logout clicked") }) {
        Text(text = "Logout")
      }
    }
  })
}

Handling TopAppBar navigation and overflow menus.

In addition to customizing the design of your TopAppBar, you can also add navigation and overflow menus to provide additional functionality to your app. To add navigation, simply add a NavigationIcon to your TopAppBar and define the navigation action. You can also add overflow menus to provide access to additional options or settings. To add an overflow menu, use the OverflowMenu component and define the menu items and actions. With these features, you can create a fully functional and customizable TopAppBar for your app.

DropdownMenu(expanded = showMenu.value, onDismissRequest = { showMenu.value = false }) {
  DropdownMenuItem(onClick = { makeToast(context, "Settings clicked") }) {
    Text(text = "Settings")
  }
  DropdownMenuItem(onClick = { makeToast(context, "Logout clicked") }) {
    Text(text = "Logout")
  }
}

Finally, TopAppBar Composeble looks like below

Let all the, together so we can achieve the same UI as per the feature image, finally your TopAppBar Compose function looks like below,

package com.topappbarjetpackcompose

import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource

@Composable
fun TopAppBarCompose() {
  val context = LocalContext.current
  val icon1 = painterResource(id = R.drawable.ic_fav)
  val icon2 = painterResource(id = R.drawable.ic_search)
  val showMenu = remember {
    mutableStateOf(false)
  }

  TopAppBar(contentColor = Color.White, title = { Text(text = "Top app bar") }, navigationIcon = {
    IconButton(onClick = {
      makeToast(context, "TopAppBar menu clicked")
    }) {
      Icon(Icons.Default.Menu, contentDescription = null)
    }
  }, actions = {
    IconButton(onClick = { makeToast(context, "Favourites") }) {
      Icon(painter = icon1, contentDescription = null)
    }
    IconButton(onClick = { makeToast(context, "Search") }) {
      Icon(painter = icon2, contentDescription = null)
    }
    IconButton(onClick = { showMenu.value = true }) {
      Icon(Icons.Default.MoreVert, contentDescription = null)
    }
    DropdownMenu(expanded = showMenu.value, onDismissRequest = { showMenu.value = false }) {
      DropdownMenuItem(onClick = { makeToast(context, "Settings clicked") }) {
        Text(text = "Settings")
      }
      DropdownMenuItem(onClick = { makeToast(context, "Logout clicked") }) {
        Text(text = "Logout")
      }
    }
  })
}

How to use with TopAppBar with Scaffold

Inside the Scaffold, add a TopAppBar composable function and pass in the necessary parameters, such as the title and navigation icon. Along with the main activity UI. Let’s run the app, your app will run and up. You can see the top bar coming with a title, and icon with the dropdown menu. I have displayed toast in click function so if you click on any dropdown and icon one toast will appear

package com.topappbarjetpackcompose

import android.content.Context
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shadow
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.topappbarjetpackcompose.ui.theme.Purple500
import com.topappbarjetpackcompose.ui.theme.TopAppBarJetpackComposeTheme

class MainActivity : ComponentActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
      TopAppBarJetpackComposeTheme {
        // A surface container using the 'background' color from the theme
        Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background) {
          CreateScaffold()
        }
      }
    }
  }
}

@Composable
fun CreateScaffold() {
  val scaffoldState = rememberScaffoldState()
  Scaffold(
    topBar = { TopAppBarCompose() }, scaffoldState = scaffoldState
  ) {
    /**
     * Create the Main UI
     */
    MainUi()
  }
}

@Composable
fun MainUi() {
  Column(
    modifier = Modifier
      .fillMaxSize(1f)
      .fillMaxHeight(1f),
    horizontalAlignment = Alignment.CenterHorizontally,
    verticalArrangement = Arrangement.Center
  ) {
    val offset = Offset(1.0f, 10.0f)
    Text(
      text = "TopAppBar Jetpack Compose",
      style = TextStyle(
        color=Purple500,
        fontWeight = FontWeight.Bold,
        fontSize = 24.sp, shadow = Shadow(
          color = Color.LightGray, offset = offset, blurRadius = 2f
        )
      ),
      textAlign = TextAlign.Center,
      modifier = Modifier.padding(16.dp)
    )
  }
}

fun makeToast(ctx: Context, msg: String) {
  Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show()
}

Conclusion

We have learned about TopAppbar jetpack using compose, If you have any queries please fell free to ask in the comment box, and I will be happy to answer that. Please share this tutorial with your friends,

Thanks for reading, Keep in touch

Read our tutorial on Jetpack Compose

Write A Comment