Jetpack Compose 的工具栏结构化行为

Ahm*_*out 4 android android-jetpack-compose android-compose-appbar

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

Toolbar您在 中定义一个小部件Activity,并可以在片段内使用onCreateOptionsMenu和访问它。onOptionsItemSelected

然而,这样的事情对于普通的 Jetpack Compose 来说是不可能的,因为无法访问中Toolbar定义的。ActivityScaffold

所以想想这个场景。你有一个Activity, ,Scaffold里面有定义,还有一个NavHostthat Scaffold。包含NavHost应用程序的所有子页面(其他可组合项)。标题可以通过导航目标侦听器进行处理,剩下的就是工具栏的操作。

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

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

小智 5

我使用了一个我命名的接口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")  
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

重点是您只需创建回调函数并在 LaunchedEffect 中运行它们。这是在脚手架的可组合项中设置工具栏属性的一种方法。接口只是将这些回调分组的一种方式,这样就不会变得太混乱。