skip to Main Content

I am using Android Studio with Jetpack Compose and Material 3. I want to create bot a topappbar and below it multiple tabs. In Material 3, Scaffold is defined as :

@Composable
fun Scaffold(
    modifier: Modifier = Modifier,
    topBar: @Composable () -> Unit = {},
    bottomBar: @Composable () -> Unit = {},
    snackbarHost: @Composable () -> Unit = {},
    floatingActionButton: @Composable () -> Unit = {},
    floatingActionButtonPosition: FabPosition = FabPosition.End,
    containerColor: Color = MaterialTheme.colorScheme.background,
    contentColor: Color = contentColorFor(containerColor),
    contentWindowInsets: WindowInsets = ScaffoldDefaults.contentWindowInsets,
    content: @Composable (PaddingValues) -> Unit
): Unit

When I assign a TopAppBar to topBar parameter, it works. Likewise if I add a TopRow with Tab(s) to topBar parameter, this also works. But how do I add a TopAppBar with Tab(s) below it.

Thanks

2

Answers


  1. Maybe you can try this:

     @OptIn(ExperimentalMaterial3Api::class)
     @Composable
     fun CustomTopBarWithTabs(
         title: String,
         selectedTabIndex: Int,
         changeTabIndex: (Int) -> Unit,
         modifier: Modifier = Modifier,
         behavior: TopAppBarScrollBehavior = 
     TopAppBarDefaults.pinnedScrollBehavior(),
     ) {
         val tabs = listOf("Home", "Settings", "Profile")
         Column(
             modifier = modifier.fillMaxWidth()
         ) {
             CenterAlignedTopAppBar(
                 scrollBehavior = behavior,
                 title = {Text(title)}
             )
             TabRow(
                 selectedTabIndex = selectedTabIndex,
             ) {
                 tabs.forEachIndexed { index, tabTitle ->
                     Tab(
                         modifier = Modifier.height(36.dp),
                         selected = selectedTabIndex == index,
                         onClick = { changeTabIndex(index) }
                     ) {
                         Text(text = tabTitle)
                     }
                 }
             }
         }
     }
    

    Create new file, and put the function inside the topBar parameter.

    Hope it works! 🙂

    Login or Signup to reply.
  2. I typically do it like this:

    val scrollState = rememberScrollState()
    
    Scaffold(
        modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
        topBar = { CenterAlignedTopAppBar() },
        content = {
            innerPadding ->
            Column(
                modifier = Modifier.padding(innerPadding)
            ) {
                TabRow(scrollState)
                Content(scrollState)
            }
        
        }
    )
    

    And if you want to raise its elevation just like the topBar when content scrolling ,maybe you could write an animation and listen the change of scrollState

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search