我无法理解错误N[5]
这是我的主机片段:
java.lang.NullPointerException: null cannot be cast to non-null type androidx.navigation.fragment.NavHostFragment
我想通过单击textView导航到SecondFragment。然后回来。
和导航图.xml文件:
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
}
}
答案 0 :(得分:1)
使用导航图的最佳方法是在创建视图之后,因为某些视图需要花一些时间才能创建,因此您的视图仍在处理或创建视图时,您可能会遇到此异常。
为了避免这种情况,您可以使用OnViewCreated()作为
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
navController = Navigation.findNavController(view)
view.imgNumbrLookUp.setOnClickListener {
navController.navigate(R.id.action_homeFragment_to_webActivity)
}
}
答案 1 :(得分:0)
您无需找到navHostFragment即可导航
val root = inflater.inflate(R.layout.fragment_host, container, false)
root.host_text_view.setOnClickListener {
Log.d("Tag", "clicked")
if (findNavController().currentDestination?.id == hostFragment)
findNavController().navigate(R.id.action_hostFragment_to_secondFragment)
}
您可以检查Kotlin方法以进行导航 https://developer.android.com/guide/navigation/navigation-navigate