Home > Blockchain >  How to set the initial start screen for a tab with jetpack compose
How to set the initial start screen for a tab with jetpack compose

Time:06-11

Right now, the start screen is the "Camera Screen" (at index 0)

enter image description here

I want to set the start screen to the "Chat Screen" (i.e index 1 not 0)

That is: When the user opens the app, the "Chat Screen" is the active screen and NOT the "Camera Screen" -- Just like how it is on whatsApp

private val tabs = listOf(
TabItem.Camera,
TabItem.Chat,
TabItem.Status,
TabItem.Call
)

@Composable
fun TabLayout(
modifier: Modifier = Modifier,
tabs: List<TabItem>,
selectedIndex: Int = 1,
onPageSelected: ((tabItem: TabItem) -> Unit)
) {

TabRow(
    selectedTabIndex = selectedIndex,
    divider = { }
) {

    tabs.forEachIndexed{index, tabItem ->

        Tab(
            selected = index == selectedIndex,
            modifier = modifier.background(MaterialTheme.colors.primary),
            onClick = {
            onPageSelected(tabItem)
        },

            text =
            {
                if (tabItem == TabItem.Camera) {
                    Icon(painter = painterResource(id = R.drawable.ic_camera), stringResource(id = R.string.icon)).toString()
                }

                else {
                    Text(
                        text = stringResource(id = tabItem.title).uppercase(Locale.ROOT),
                        style = MaterialTheme.typography.caption,
                    )
                }

            },
        )
    }
  }
}

CodePudding user response:

You need to initialize your selectedIndex variable that you're passing into TabRow as 1.

CodePudding user response:

You can try to use state for the selected tab:

@Composable
fun TabLayout(
modifier: Modifier = Modifier,
tabs: List<TabItem>,
selectedIndex: Int = 1,
onPageSelected: ((tabItem: TabItem) -> Unit)
) {
 var tabIndex by remember { mutableStateOf(selectedIndex) }

TabRow(
  selectedTabIndex = tabIndex,
  divider = { }
 ) {

tabs.forEachIndexed{index, tabItem ->

    Tab(
        selected = index == tabIndex,
        modifier = modifier.background(MaterialTheme.colors.primary),
        onClick = {
          tabIndex = index
          onPageSelected(tabItem)
        },
  • Related