Jetpack Compose 中的视觉导航图表示?

Ars*_*ius 5 android android-studio android-jetpack android-jetpack-navigation android-jetpack-compose

Jetpack 导航组件nav_graph.xml在片段之间具有很好的文件可视化表示,但是如果我们为 Jetpack Compose 使用导航组件,则不支持nav_graph.xml可组合功能。那么问题是如何直观地看到可组合小部件和屏幕之间的导航图,类似于我们nav_graph.xml在 Android Studio 中可以看到的那样?

小智 -1

Android Studio 目前不支持 Jetpack Compose Navigation 中可组合函数的可视化。但是,作为解决方法,您可以使用 Jetpack Navigation 库并预览片段内的可组合小部件。


解决方法:

为了使预览正常工作,我们可以使用Jetpack Navigation 库(非 compose 版本)来处理应用程序内部的导航并预览图形。因此,我们需要在Fragment.

XML为您创建资源Fragment,根元素为ComposeView

<androidx.compose.ui.platform.ComposeView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/composeView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:composableName="com.example.myapplication.HomeScreenKt.PreviewHome" />
Run Code Online (Sandbox Code Playgroud)

tools:composableName属性中指定带注释的函数的完整路径@Preview

然后Fragment为您的可组合小部件创建一个(如何):

class HomeFragment : Fragment() {

    private var _binding: FragmentHomeBinding? = null
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View = FragmentHomeBinding
        .inflate(inflater, container, false)
        .also { _binding = it }
        .root

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initComposeView()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    private fun initComposeView() {
        with(binding.composeView) {
            setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
            setContent {
                HomeScreen()
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

创建图表res/navigation/home_graph并添加片段:

<?xml version="1.0" encoding="utf-8"?>
<navigation 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"
    android:id="@+id/home_graph"
    app:startDestination="@id/homeFragment">

    <fragment
        android:id="@+id/homeFragment"
        android:name="com.example.myapplication.HomeFragment"
        android:label="HomeFragment"
        tools:layout="@layout/fragment_home" />
</navigation>
Run Code Online (Sandbox Code Playgroud)

不要忘记指定tools:layout标签,因为它告诉 Android Studio 绘制XML文件的预览。

构建项目,您将在导航图中看到可组合函数的工作预览! 在此输入图像描述