如果是按照以前老版本xml的方式来实现:底部导航栏、顶部toolbar、悬浮按钮floatingActionButtonPosition,代码会比较多而且很难懂,现在我们来看看使用神奇的compose来实现,效果图:
依赖:
implementation 'androidx.compose.material:material:1.2.1'
代码:
@Composable
fun MainPage() {
//当前选择的NavItem
var selectIndex by remember { mutableStateOf(0) }
val navTextList = listOf("主页", "发现", "我的")
//图标
val iconList = listOf(Icons.Default.Home, Icons.Default.Favorite, Icons.Default.AccountBox)
Scaffold(
topBar = {
TopAppBar(
navigationIcon = {
IconButton(
onClick = {}
) {
Icon(Icons.Filled.Menu, null)
}
},
title = {
Text("stars-one的测试应用")
},
actions = {
IconButton(
onClick = {}
) {
Icon(Icons.Filled.Share, null)
}
IconButton(
onClick = {}
) {
Icon(Icons.Filled.Settings, null)
}
},
// backgroundColor = colorResource(id = R.color.purple_700)
)
},
floatingActionButton = {
FloatingActionButton(onClick = { /*TODO*/ }) {
Icon(imageVector = Icons.Default.Add, contentDescription = null)
}
},
bottomBar = {
// BottomNavigation(backgroundColor = colorResource(id = R.color.white)) { // 底部背景颜色
BottomNavigation {
navTextList.forEachIndexed { index, str ->
BottomNavigationItem(
label = { Text(str) },
selected = index == selectIndex,
//选中选项的颜色 (text\icon\波纹)
selectedContentColor = colorResource(id = R.color.white),
//未选中选项的颜色 (text\icon\波纹)
unselectedContentColor = colorResource(id = R.color.black_bottomnav),
// 默认为true,底部的字未选中时是否显示
alwaysShowLabel = false,
onClick = { selectIndex = index },
icon = {
Icon(imageVector = iconList[index], contentDescription = null)
})
}
}
},
//注意此参数,可以实现图中那种被裁剪的效果,前提是上面的cutoutShape也有设置
floatingActionButtonPosition = FabPosition.End
) {
//这里是主界面
//根据底部导航选中的下标改变展示的页面
when (selectIndex) {
0 -> Text("这是首页")
1 -> Text("这是发现")
2 -> Text("这是我的")
}
}
}
是不是很简单,这样就可以了,谢谢观赏
顶部状态栏的高度
modifier = Modifier.systemBarsPadding()
可以配合toolbar一起使用
完美的底部导航栏
本人在多个项目中使用,已经修复使用中出现的bug
下载地址为:https://download.csdn.net/download/wy313622821/88225624
本文展示了如何使用JetpackCompose来简洁地实现底部导航栏、顶部ToolBar和悬浮按钮,对比了传统XML方式的复杂性,并提供了具体的代码示例。通过Compose,代码变得更易理解和维护。
1346

被折叠的 条评论
为什么被折叠?



