点击topbar中的iconbutton,出现菜单
@Composable
fun HomeScreen() {
Column {
MyTopBar()
Text(text = "你好")
}
}
如图所示,出现的菜单并未把“你好”撑开
添加控制变量,放在最外面
var isMenuVisible by mutableStateOf(false)
方法一:topbar 和 DropDownMenu垂直线性结构
点击按钮修改值,菜单显示 。
@Composable
private fun MyTopBar() {
Column() {
TopAppBar(
title = { Text("Simple TopAppBar") },
navigationIcon = {
IconButton(onClick = { /* doSomething() */ }) {
Icon(Icons.Filled.Menu, contentDescription = null)
}
},
actions = {
// RowScope here, so these icons will be placed horizontally
IconButton(onClick = { /* doSomething() */ }) {
Icon(Icons.Filled.Search, contentDescription = "find someone")
}
IconButton(onClick = { isMenuVisible = !isMenuVisible }) {
Icon(Icons.Filled.Add, contentDescription = "add")
}
}
)
if (isMenuVisible) {
Box(
Modifier.align(Alignment.End) // 靠右
) {
DropdownMenu(
expanded = true,
onDismissRequest = { isMenuVisible = false },
) {
DropdownMenuItem(
onClick = { /* Handle menu item click */ }) {
Row() {
Icon(Icons.Filled.Add, contentDescription = "add new friends")
Text("添加新朋友")
}
}
DropdownMenuItem(
onClick = { /* Handle menu item click */ }) {
Row() {
Icon(Icons.Filled.Add, contentDescription = "add new groups")
Text("添加新群组")
}
}
}
}
}
}
}
方法二(推荐)
contentAlignment = Alignment.TopEnd
Box(
modifier = Modifier
.padding(end = 10.dp),
contentAlignment = Alignment.TopEnd
) {
DropdownMenu(
modifier = Modifier.background(color = MaterialTheme.colors.background),
expanded = isMenuVisible,
onDismissRequest = {
isMenuVisible = false
}
) {
DropdownMenuItem(
onClick = {
isMenuVisible = false
viewState.showAddDialog()
}
){
Text(
text = "添加好友",
style = TextStyle(fontSize = 18.sp)
)
}
DropdownMenuItem(
onClick = {
isMenuVisible = false
viewState.showAddDialog()
}
){
Text(
text = "加入群聊",
style = TextStyle(fontSize = 18.sp)
)
}
}
}