I have a button in fragment A and when I click on fragment A, I want it to be redirected to fragment B. How to achieve this in kotlin? Right now I am using this code but app crash.
btntest.setOnClickListener {
var intent = Intent(view.context, FragmentB::class.java)
startActivity(intent)
}
CodePudding user response:
I'd suggest you take a look on
Make sure to give an ID to each fragment (that's what you'll use to navigate between them later). Additionally, you can use app:startDestination
in order to set the first fragment to be shown.
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
app:startDestination="@id/blankFragment">
<fragment
android:id="@ id/blankFragment"
android:name="com.example.cashdog.cashdog.BlankFragment"
android:label="@string/label_blank"
tools:layout="@layout/fragment_blank" />
</navigation>
Then, in the activity/fragment that will be hosting the fragments, add a FragmentContainerView
and set the graph to the one you created.
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.fragment.app.FragmentContainerView
android:id="@ id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_graph" />
</androidx.constraintlayout.widget.ConstraintLayout>
Finally, in order to navigate between fragments, use this in the Activity that is hosting the navigation (use getActivity()
if a Fragment is hosting the navigation).
// as per defined in your FragmentContainerView
val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
val navController = navHostFragment.navController
// Navigate using the IDs you defined in your Nav Graph
navController.navigate(R.id.blankFragment)
Source: https://developer.android.com/guide/navigation/navigation-getting-started
Edit: if you want to access the controller within your Fragment
, use activity?.supportFragmentManager
to get the fragment manager.