如何在Compose中使用findNavController()

10

我目前正在为一款Kotlin应用做代码重构。我想通过在Compose视图中按下按钮来切换到另一个片段。我知道Compose有自己的导航器,但是我能否在Compose文件中以某种方式使用findNavController()函数?我尝试将一个函数发送到Compose文件,但仍然出现错误:

java.lang.UnsupportedOperationException: Cannot add views to ComposeView; only Compose content is supported

当前代码:

片段中的代码:

binding.composeProgram.setContent {
        MdcTheme {
            ProgramContent(
                viewModel = viewModel,
                navigationController = {
                    findNavController().navigate(
                        R.id.exercise_details,
                        ExerciseDetailFragmentArgs(396).toBundle(),
                        null,
                        null
                    )
                }
            )
        }
    }

Compose文件:

@Composable
fun ProgramContent(
    viewModel: ProgramFragmentViewModel,
    navigationController:  () -> (Unit)
) {
    Button(onClick = {
        navigationController()
    }){}
}

解决方法: 我必须在xmlns文件中添加一行:
android:transitionGroup="true"

因此,在xmlns文件中,它将看起来像这样:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    style="@style/AppTheme.Fragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:transitionGroup="true"
    >

<androidx.compose.ui.platform.ComposeView
        android:id="@+id/compose_program"
        android:layout_width="match_parent"
        android:layout_height="0.dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        />
...

1
谢谢,transitionGroup解决了我的问题。你能把它作为一个答案添加进去吗? - lotdrops
1个回答

0
我必须在xmlns文件中添加一行。
android:transitionGroup="true"

所以在xmlns文件中,它会看起来像这样:
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    style="@style/AppTheme.Fragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:transitionGroup="true"
    >

<androidx.compose.ui.platform.ComposeView
        android:id="@+id/compose_program"
        android:layout_width="match_parent"
        android:layout_height="0.dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        />
...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接