Не могу понять, в чем причина ошибки java.lang.NullPointerException: null cannot be cast to non-null type androidx.navigation.fragment.NavHostFragment
Это мой хост-фрагмент:
class HostFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root = inflater.inflate(R.layout.fragment_host, container, false)
// error here
val navHostFragment = requireActivity().supportFragmentManager.findFragmentById(R.id.hostFragment) as NavHostFragment
//
val navController = navHostFragment.navController
root.host_text_view.setOnClickListener {
Log.d("Tag", "clicked")
navController.navigate(R.id.action_hostFragment_to_secondFragment)
}
return root
}
}
Я хочу перейти к SecondFragment, щелкнув textView. И назад.
И файл .xml nav graph:
<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/nav_graph"
app:startDestination="@id/hostFragment">
<fragment
android:id="@+id/hostFragment"
android:name="com.example.test.HostFragment"
android:label="fragment_host"
tools:layout="@layout/fragment_host" >
<action
android:id="@+id/action_hostFragment_to_secondFragment"
app:destination="@id/secondFragment" />
</fragment>
<fragment
android:id="@+id/secondFragment"
android:name="com.example.test.SecondFragment"
android:label="fragment_second"
tools:layout="@layout/fragment_second" >
<action
android:id="@+id/action_secondFragment_to_hostFragment"
app:destination="@id/hostFragment" />
</fragment>
</navigation>
supportFragmentManager.findFragmentById(R.id.hostFragment)
ищет Фрагмент наandroid:id="@+id/hostFragment"
в макете вашего Действия. Можете ли вы включить макет своей деятельности и где вы добавили свойNavHostFragment
в свой макет? - person ianhanniballake   schedule 04.10.2020