首页 > 解决方案 > Jetpack Compose 的工具栏结构化行为

问题描述

想象一下 Android 中工具栏的常见行为。

您在 中定义一个Toolbar小部件Activity,并且可以使用onCreateOptionsMenuonOptionsItemSelected在您的片段中访问它。

但是,使用普通的 Jetpack Compose 是不可能的,因为无法访问'sToolbar中定义的.ActivityScaffold

所以想想这个场景。你有一个Activity, 里面有Scaffold定义,NavHost里面有一个 that Scaffold。包含应用程序的NavHost所有子页面(其他可组合)。标题可以处理查看导航目的地监听器,剩下的是工具栏的操作。

您将如何根据您所在的当前页面/可组合项更改工具栏操作?并处理对这些操作的点击?

PS:在每个页面中使用工具栏并不是一个解决方案,因为它会在动画页面之间切换时带来糟糕的用户体验,工具栏会在每个页面上消失并重新出现。

标签: androidandroid-jetpack-compose

解决方案


我使用了一个我命名的接口ToolbarController,其中包含回调方法,这些方法可以设置调用脚手架时使用的变量的值TopAppBar

@Composable  
fun MyApp(){  
  
 var toolbarTitle by remember{ mutableStateOf("") }  
  
 // ToolbarController would be some interface you have defined  
 val toolbarController = object: ToolbarController {  
        override fun setTitle(title: String){  
            toolbarTitle = title  
        }  
    }  
  
 Scaffold(  
    topBar = { 
       TopAppBar( title = { Text(text = toolbarTitle) }  )  
    }  
 ){  
    SomeScreen(toolbarController = toolbarController)  
 }  
}  
  
@Composable  
fun SomeScreen(  
    toolbarController: ToolbarController  
) {  
    //I'm not 100% sure I need to use an effect here, but I think so...
    //And I'm not sure this is the right one. It is not a coroutine I call,
    //but it of course works with normal calls. Also SideEffect runs on every
    //recompose according to the docs, and that's not what we want.
    //https://developer.android.com/jetpack/compose/side-effects
    LaunchedEffect(true){
       toolbarController.setTitle("Some screen title")  
    }
}

编辑:它很容易用于任何工具栏属性,您可以创建这样的界面:

interface ToolbarController{
    fun configToolbar(
        title: String = "",
        navigationIcon: IconButton? = null,
        actions: List<IconButton> = listOf()
    )
}

关键是您只需创建回调函数并在 LaunchedEffect 中运行它们。这是从脚手架中的可组合项中设置工具栏属性的一种方法。接口的东西只是对这些回调进行分组的一种方式,所以它不会变得太乱。


推荐阅读