我想在我的应用程序中使用导航。
在main_activity
中声明
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!-- Main content -->
<fragment
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_graph" />
</androidx.constraintlayout.widget.ConstraintLayout>
那么我想使用动作从片段1转到片段2更新我添加了更多代码
class LoginFragment2 : Fragment(){
private lateinit var viewModel : LoginViewModel2
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fr_login, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initViews()
}
private fun initViews() {
btn_registration.setOnClickListener {
// Navigation.findNavController(it).navigate(R.id.action_loginFragment2_to_newTypeAccountFragment)
// navController = Navigation.findNavController(view)
// findNavController(it).navigate(R.id.action_loginFragment2_to_newTypeAccountFragment)
this.findNavController().navigate(R.id.action_loginFragment2_to_newTypeAccountFragment)
}
}
我尝试了几个选项(但没有一个对我没有帮助(
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.app.peshkariki, PID: 22658
java.lang.IllegalStateException: View androidx.constraintlayout.widget.ConstraintLayout{ca39b84
V.E...... ........ 0,0-720,1360} does not have a NavController set
如何正确使用它?
导航图(事实上,它很大,但我会发布与此片段相关的小部分(
<?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/nav_graph"
app:startDestination="@id/mainActivity">
<fragment
android:id="@+id/loginFragment2"
android:name="com.app.peshkariki.newPesh.ui.login.LoginFragment2"
android:label="LoginFragment2"
tools:layout="@layout/fr_login">
<action
android:id="@+id/action_loginFragment2_to_newTypeAccountFragment"
app:destination="@id/newTypeAccountFragment" />
</fragment>
</navigation>
您呼叫了NavHostFragment
,但不需要。
将其更改为
btn_registration.setOnClickListener {
this.findNavController()
.navigate(R.id.action_loginFragment2_to_newTypeAccountFragment)
}
将其放入onViewCreated
:
val navHostFragment = supportFragmentManager.findFragmentById(R.id.my_nav_host_fragment) as NavHostFragment
val navController = navHostFragment.navController
你也可能想做这个课程