Android Kotlin – Navigation Add Host Fragment and Connect Destinations with Actions

On the activity’s layout XML file that you want to add Host Fragment, add the following code.

<fragment
   android:id="@+id/navHostFragment"
   android:name="androidx.navigation.fragment.NavHostFragment" 
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   app:navGraph="@navigation/navigation"
   app:defaultNavHost="true"
   />
  • android:name – class name
  • app:navGraph – which navigation resource to use
  • app:defaultNavHost=”true” – intercepts the system Back button

Now, go navigation.xml, switch to Design and add a new Destination by clicking the + symbol at the top

, <span>Android Kotlin – Navigation Add Host Fragment and Connect Destinations with Actions</span>, KandZ

To set it the first destination of the navigation click Set Start Destination

To create an action, add a second destination, and then click the circle on the first destination and drag it to the second destination.

, <span>Android Kotlin – Navigation Add Host Fragment and Connect Destinations with Actions</span>, KandZ

To navigate with the action you created you need to create an onClickListener and find the NavController. Then navigate with the action you created

button.setOnClickListener { view ->
   Navigation.findNavController(view).navigate(R.id.action_firstFragment_to_secondFragment)
}

You can also use

button.setOnClickListener(Navigation.createNavigateOnClickListener(R.id.action_firstFragment_to_secondFragment, null))

 

 

35280cookie-checkAndroid Kotlin – Navigation Add Host Fragment and Connect Destinations with ActionsAndroid Kotlin – Navigation Add Host Fragment and Connect Destinations with Actions

Related posts