Mar*_*rat 9 android-jetpack-compose
我们的应用程序中有底部导航,我们希望在屏幕中添加滑动行为,这样如果用户向右/向左滑动,那么他/她应该导航到下一个屏幕。
我知道伴奏有HorizontalPager
制表符。但我想知道我们是否可以通过底部导航来实现这种行为。
正如您在材料设计指南中所看到的:
在内容区域上使用滑动手势不会在视图之间导航。
还:
避免使用横向运动在视图之间进行转换。
但是,如果你真的想这样做,你可以这样做:
fun BottomNavSwipeScreen() {
// This scope is necessary to change the tab using animation
val scope = rememberCoroutineScope()
// I'm using a list of images here
val images = listOf(R.drawable.img1, ...)
// This page state will be used by BottomAppbar and HorizontalPager
val pageState = rememberPagerState(pageCount = images.size)
val scaffoldState = rememberScaffoldState()
Scaffold(
scaffoldState = scaffoldState,
bottomBar = {
BottomAppBar(
backgroundColor = MaterialTheme.colors.primary,
content = {
for (page in images.indices) {
BottomNavigationItem(
icon = {
Icon(Icons.Filled.Home, "Page $page")
},
// here's the trick. the selected tab is based
// on HorizontalPager state.
selected = page == pageState.currentPage,
onClick = {
// When a tab is selected,
// the page is updated
scope.launch {
pageState.animateScrollToPage(page)
}
},
selectedContentColor = Color.Magenta,
unselectedContentColor = Color.LightGray,
label = { Text(text = "Page $page") }
)
}
}
)
},
) {
HorizontalPager(
state = pageState,
offscreenLimit = 2
) { page ->
Image(
painterResource(id = images[page]),
null,
modifier = Modifier
.fillMaxSize(),
contentScale = ContentScale.Crop
)
}
}
}
Run Code Online (Sandbox Code Playgroud)
结果如下:
归档时间: |
|
查看次数: |
5922 次 |
最近记录: |