以下示例代码 CameraFragment.kt 和 activity_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))