android - Jetpack Compose 的工具栏结构化行为

标签 android android-jetpack-compose android-compose-appbar

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

您在 Activity 中定义了一个 Toolbar 小部件,并且可以使用 onCreateOptionsMenuonOptionsItemSelected 在您的 fragment 。

但是,对于普通的 Jetpack Compose 来说,这样的事情是不可能的,因为无法访问在 Activity 中定义的 Toolbar脚手架.

所以想想这个场景。您有一个 Activity,其中定义了 Scaffold,并且在该 Scaffold 中有一个 NavHostNavHost 包含应用程序的所有子页面(其他可组合项)。 title可以处理查看Navigation Destination Listener,剩下的就是Toolbar的Actions。

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

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

最佳答案

我使用了一个名为 ToolbarController 的接口(interface),它包含回调方法,可以设置调用脚手架的 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 中运行它们。这是从脚手架的可组合项中设置工具栏属性的一种方法。界面内容只是对这些回调进行分组的一种方式,因此它不会变得太困惑。

关于android - Jetpack Compose 的工具栏结构化行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67920365/

相关文章:

android - 我不明白为什么当我将列表更改为 mutableStateOf 时 Jetpack Compose 不重新组合?

android - 类型不匹配。必需 : Alignment. 水平找到:对齐

android - 如何在 Jetpack Compose 中传递条件参数?

安卓 "No content provider found for permission revoke"

java - Activity 重新创建后操作栏标题消失

android - 为什么当我从函数中删除 null 时 android studio 会出错?

android - 设置摘要描述当前值

android - 如何在 Jetpack compose 中使用 EditText 或 TextInput 小部件?