Navigation Component: Storyboard for android

Abhiraj Khare
IOT Android Things
Published in
3 min readFeb 18, 2019

--

Navigation component can be very helpful in creating complex ui navigation flow. It has navigation graph similar to storyboard in iOS.

We have to use following dependencies to use navigation controller in our project.

dependencies {
implementation "android.arch.navigation:navigation-fragment- ktx:2.3.0-alpha06"
implementation "android.arch.navigation:navigation-ui-ktx:2.3.0-alpha06"
}

Then we have to create navigation resource file which will hold UI screens flow.

Navigation controllers is best suited for apps or module having one activity and multiple fragment. Each activity hold its own navigation view.

Below you can see “No NavHostFragment found”. So we have to define a NavHostFragment in our launching activity XML.

<fragment
android:id="@+id/navigation_host_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="androidx.navigation.fragment.NavHostFragment"
app:navGraph="@navigation/navigation_flow"
app:defaultNavHost="true"
/>

Here “navGraph” attribute associates navigation xml with NavHostFragment. And “defaultNavHost” ensures that this NavHostFragment intercept system back button.

Once this host fragment is defined, you must see your navigation view as:

Lets add a fragment in this view by clicking +button.

Once “StartFragment” is shown in navigation view, double click on it to edit its xml. Add two button here.

Now we will create two destination fragment (FirstFragment, SecondFragment), and link them in navigation view.

Now if you see navigation xml, two action are created within StartFragment. These action represent links between StartFragment and FirstFragment/SecondFragment.

<action android:id="@+id/action_startFragment_to_firstFragment" app:destination="@id/firstFragment"/>
<action android:id="@+id/action_startFragment_to_secondFragment" app:destination="@id/secondFragment"/>

Setting destination fragment on click of button

Using NavController navigate() method, we can open destination fragment on click of button using above defined action destination id.

button.setOnClickListener({
it
.findNavController().navigate(R.id.action_startFragment_to_firstFragment)
})

Passing bundle arguments from one fragment to another.

var bundle:Bundle = Bundle()
bundle.putString("bundleKey", "Hello World !!!")
it.findNavController().navigate(R.id.action_startFragment_to_secondFragment, bundle)

We can retrieve above passed argument in destination fragment by:

arguments?.getString("bundleKey")

You can find full source code at:

Also check how to create UI using ConstraintLayout here

--

--