我是否可以始终使用findNavController(mView)在Android Studio 3.5.2中查找NavController

问题描述 投票:0回答:1

以下示例代码CameraFragment.ktactivity_main.xml来自camera-samples项目。

它使用findNavController(requireActivity(), R.id.fragment_container)找到NavController。

我认为这很复杂,我是否可以始终使用findNavController(mView)查找NavController?就像代码A?

CameraFragment.kt

private fun updateCameraUi() {    
       ...          
       Navigation.findNavController(requireActivity(), R.id.fragment_container).navigate(
              CameraFragmentDirections.actionCameraToGallery(outputDirectory.absolutePath))

}

activity_main.xml

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:keepScreenOn="true"
    tools:context=".MainActivity">

    <fragment
        android:id="@+id/fragment_container"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/nav_graph" />

</FrameLayout>

代码A

private lateinit var mView: View 

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


Navigation.findNavController(mView).navigate(
           CameraFragmentDirections.actionCameraToGallery(outputDirectory.absolutePath))
android android-studio kotlin
1个回答
0
投票

在片段中甚至不需要使用Navigation.findNavController(mView)-您可以根据NavHostFragment.findNavController(this)使用NavHostFragment从片段中找到Navigate to a destination documentation

但是,您也可以使用Navigation.findNavController(mView)或片段中的任何视图。

[仅在拥有活动时才想使用findNavController(requireActivity(), R.id.fragment_container)。当它起作用时,有更简单的方法可以执行相同的操作。

© www.soinside.com 2019 - 2024. All rights reserved.