Reputation: 1044
I searched and implemented Jetpack compose samples. I implemented the below navigation codelab sample too.
https://github.com/googlecodelabs/android-compose-codelabs/tree/main/NavigationCodelab
I have a problem here. When i clicked something at the tab, we navigated to a composable and pıut that composable to the stack. When i clicked back, the previous composeable is shown.
In my navigation component app which is not using jetpack compose, for example say that there are 3 tabs : Home, Favorite, Settings. I clicked Favorite, Settings, Home, Favorite, Settings. When i pressed back button, home fragment is shown. Then, when i pressed back button again, app is closed.
In my compose navigation app, i do the same action(clicked Favorite, Settings, Home, Favorite, Settings). In order to close the app, i need to press back button 5 times. This is my problem. I want to have the same behaviour with navigation component. I want that when i clicked back button starting destination fragment should be shown, then, when i clicked back button again, app should be closed. How to do that ?
Upvotes: 2
Views: 2717
Reputation: 21
//tab sealed class
typealias ComposableFun = @Composable () -> Unit
sealed class TabsItem(val title: String, val screen: ComposableFun){
object HomeScrenn: TabsItem(title = "Home", { Home() })
object FavScreen: TabsItem(title = "fav", { fav()})
object SetingScreen: TabsItem(title = "Setting"{Setting()},
}
//you can add your tabs here
@Composable
fun SectionTabScreen() {
val tabs = listOf(
TabsItem.Home,
TabsItem.Fav,
TabsItem.Setting,
)
val pagerState = rememberPagerState()
Scaffold{
Column {
Tabs(tabs = tabs, pagerState = pagerState)
TabsContent(tabs = tabs, pagerState = pagerState)
}
}
}
@Composable
fun Tabs(tabs: List<TabsItem>, pagerState: PagerState) {
val scope = rememberCoroutineScope()
// OR ScrollableTabRow()
ScrollableTabRow(
modifier = Modifier.fillMaxWidth(),
selectedTabIndex = pagerState.currentPage,
backgroundColor = MaterialTheme.colors.background,
// contentColor = Color.White,
edgePadding = 0.dp,
indicator = { tabPositions ->
TabRowDefaults.Indicator(
Modifier.pagerTabIndicatorOffset(pagerState, tabPositions)
)
}){
tabs.forEachIndexed { index, tab ->
// OR LeadingIconTab()
Tab(
text = {
Text(
text = tab.title,
fontSize = MaterialTheme.typography.h6.fontSize,
)},
selected = pagerState.currentPage == index,
onClick = {
scope.launch {
pagerState.animateScrollToPage(index)
}
},
)
}
}
}
@Composable
fun TabsContent(tabs: List<TabsItem>, pagerState: PagerState) {
HorizontalPager(state = pagerState, count = tabs.size) { page ->
tabs[page].screen()
}
}
Upvotes: 2
Reputation: 21
have you tried using Accompanist
// Pager
implementation "com.google.accompanist:accompanist-pager:0.23.0"
// Pager Indicators
implementation "com.google.accompanist:accompanist-pagerindicators:0.23.0"
Upvotes: 0