Adding the Navigation component to an Android project in Kotlin
buildscript {
ext {
...
version_navigation = "1.0.0-beta01" // Update based on version at https://developer.android.com/jetpack/androidx/releases/navigation
}
...
}
dependencies {
...
implementation "android.arch.navigation:navigation-fragment-ktx:$version_navigation"
implementation "android.arch.navigation:navigation-ui-ktx:$version_navigation"
}
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<fragment
android:id="@+id/myNavHostFragment" // ID for Navigation fragment
android:name="androidx.navigation.fragment.NavHostFragment" // Add this. Don't ask, just do it. This is the host for all the other fragments
android:layout_width="match_parent"
android:layout_height="match_parent"
app:navGraph="@navigation/navigation" // And this. Points to navigation.xml in res/navigation folder which is where the Navigation Graph lives
app:defaultNavHost="true" /> // And this. Allows Navigation component to control system back key
</LinearLayout>
</layout>
Create a new Resource file called navigation.xml in the res/navigation folder and switch to the Design view. You can now pull in Activities and Fragments and link them together. To link the Navigation Graph action (the link between two destinations) to a UI component use the built-in setOnClickListener:
class TitleFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val binding: FragmentTitleBinding = DataBindingUtil.inflate(
inflater, R.layout.fragment_title, container, false
)
binding.playButton.setOnClickListener (
Navigation.createNavigateOnClickListener(R.id.action_titleFragment_to_gameFragment) // Built-in onClickListener. The resource pointed to here is auto-generated when a link is drawn between the 2 Fragments in the Navigation Graph
)
return binding.root
}
}
