Android KotlinAndroid tutorial

Navigation component android example kotlin

Navigation component android example

Navigation component is a part of Android Jetpack library that helps you implement navigation functionality in your Android app. It provides a simple and consistent way to navigate between different screens or destinations in your app, such as activities, fragments, or dialogs. The navigation component provides a range of benefits, including:

What is a navigation component?

  • Simplifying navigation code: The navigation component uses a declarative approach to define navigation paths in your app, reducing the need for boilerplate code and making it easier to manage navigation.
  • Handling common scenarios: The navigation component provides built-in support for common navigation scenarios, such as handling the back button, passing data between destinations, and handling deep linking.
  • Providing a visual editor: Android Studio includes a visual editor for the navigation component, which makes it easy to create and modify navigation graphs.

To use the navigation component in your app, you need to follow these steps:

  1. Add the navigation component to your project by including the following dependency in your app-level build.gradle file:

implementation "androidx.navigation:navigation-fragment-ktx:$version_navigation"

  1. Create a navigation graph by defining the destinations and navigation paths in an XML file. You can use the visual editor in Android Studio to create the graph or write the XML code manually.
  2. Define the navigation actions in your code by calling the NavController object to navigate between destinations. You can also use the NavigationUI class to set up common navigation patterns, such as the navigation drawer or bottom navigation.
  3. Connect your destinations to the navigation graph by adding a NavHostFragment to your layout and setting it up in your code.

By following these steps, you can use the navigation component to handle navigation in your Android app, providing a simple and consistent experience for your users.

What are different navigation components?

The Navigation component in Android Jetpack provides a set of core components that you can use to implement navigation in your app. Here are the main navigation components:

  1. Navigation Graph: A navigation graph is an XML resource that defines the navigation paths and destinations in your app. It is used to represent the structure of your app’s navigation, and it provides a visual representation of the app’s navigation paths.
  2. NavHost: A NavHost is a container for hosting navigation destinations. It is typically used as a fragment, and it provides a space for the Navigation component to swap out destinations as the user navigates through the app.
  3. NavController: The NavController is an object that manages app navigation within a NavHost. It provides methods for navigating between destinations and handling back navigation.
  4. NavDirections: NavDirections is a class that represents a navigation action from one destination to another. It is used to define the navigation paths in your navigation graph.
  5. Safe Args: Safe Args is a plugin that generates type-safe code for passing data between destinations in your app. It provides compile-time safety and reduces the risk of runtime errors.
  6. BottomNavigationView: BottomNavigationView is a component that provides a tabbed navigation pattern at the bottom of the screen. It is often used in conjunction with the Navigation component to provide a consistent navigation experience across different destinations.

Overall, these navigation components work together to provide a flexible and powerful navigation system for your Android app.

Navigation component android example Kotlin

Lets start to make an example to easy understanding how to used it in your App. So firstly create a android project and sync it. once your project successfully build follow below steps.

 

Stes 1 : Add the Navigation component dependency to your app-level build.gradle file:

plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
}

android {
    namespace 'com.example.navigationgraphexample'
    compileSdk 33

    defaultConfig {
        applicationId "com.example.navigationgraphexample"
        minSdk 23
        targetSdk 33
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    dataBinding{
        enabled true
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.6.1'
    implementation 'com.google.android.material:material:1.8.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.5'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'

    implementation "androidx.navigation:navigation-fragment-ktx:2.5.3"
    implementation "androidx.navigation:navigation-ui-ktx:2.5.3"
}

 

Step 2 : Create a navigation graph XML file to define the navigation paths and destinations in your app. For example:

in the res –> create a new folder name navigation in this folder create a new xml file login_nav_flow.xml and add below code.

<?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/login_nav_flow"
    app:startDestination="@id/landingFragment2">
    <fragment
        android:id="@+id/landingFragment2"
        android:name="com.example.navigationgraphexample.fragment.LandingFragment"
        android:label="LandingFragment" >
        <action
            android:id="@+id/action_landingFragment2_to_loginFragment2"
            app:destination="@id/loginFragment2"
            app:popUpTo="@id/landingFragment2"
            app:popUpToInclusive="true" />
        <action
            android:id="@+id/action_landingFragment2_to_signUpFragment3"
            app:destination="@id/signUpFragment"
            app:popUpTo="@id/landingFragment2"
            app:popUpToInclusive="true" />


    </fragment>
    <fragment
        android:id="@+id/loginFragment2"
        android:name="com.example.navigationgraphexample.fragment.LoginFragment"
        android:label="LoginFragment" >

        <action
            android:id="@+id/action_loginFragment2_to_welcomeActivity"
            app:destination="@id/welcomeActivity"
            app:popUpTo="@id/loginFragment2"
            app:popUpToInclusive="true" />
    </fragment>
    <fragment
        android:id="@+id/signUpFragment"
        android:name="com.example.navigationgraphexample.fragment.SignUpFragment"
        android:label="SignUpFragment" >

        <action
            android:id="@+id/action_signUpFragment_to_otpFragment"
            app:destination="@id/otpFragment"
            app:popUpTo="@id/signUpFragment"
            app:popUpToInclusive="true" />
    </fragment>
    <fragment
        android:id="@+id/otpFragment"
        android:name="com.example.navigationgraphexample.fragment.OtpFragment"
        android:label="OtpFragment" >

        <action
            android:id="@+id/action_otpFragment_to_welcomeActivity"
            app:destination="@id/welcomeActivity"
            app:popUpTo="@id/otpFragment"
            app:popUpToInclusive="true" />
    </fragment>
    <activity
        android:id="@+id/welcomeActivity"
        android:name="com.example.navigationgraphexample.fragment.WelcomeActivity"
        android:label="WelcomeActivity" />
</navigation>

Step 3 : In your activity, set up a NavHostFragment to display the navigation graph. For example:

package com.example.navigationgraphexample

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.navigation.NavController
import androidx.navigation.findNavController
import androidx.navigation.ui.NavigationUI
import com.example.navigationgraphexample.databinding.ActivityMainBinding
import com.example.navigationgraphexample.fragment.LandingFragment

class MainActivity : AppCompatActivity() {
    private lateinit var binding:ActivityMainBinding
    private lateinit var navController:NavController
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this@MainActivity, R.layout.activity_main)

        navController = this.findNavController(R.id.mainActivityFragment)
        NavigationUI.setupActionBarWithNavController(this@MainActivity, navController)
        return setContentView(binding.root)

    }

    override fun onSupportNavigateUp(): Boolean {
        return navController.navigateUp()
    }
}

Step3.1 your main_activity.xml file code.

<?xml version="1.0" encoding="utf-8"?>
<layout
    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">
<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

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

</androidx.constraintlayout.widget.ConstraintLayout>
</layout>

 

Step4 : Create the used fragments in your all flow. 

in this example i am using 4 fragments ( landingFragment, loginFragment, signUpFragment, otpFragment, welcomeActivity ). In your fragment, use the NavController object to navigate to other destinations.

1. Fragment LandingFragment Source code.

LandingFragment.xml

<?xml version="1.0" encoding="utf-8"?>
<layout
    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"  >
<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".fragment.LandingFragment">

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/btnLogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Login"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.14"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.appcompat.widget.AppCompatButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="SignUp"
        android:id="@+id/btnSignUp"
        app:layout_constraintBottom_toBottomOf="@+id/btnLogin"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.75"
        app:layout_constraintStart_toEndOf="@+id/btnLogin"
        app:layout_constraintTop_toTopOf="@+id/btnLogin" />


</androidx.constraintlayout.widget.ConstraintLayout>
</layout>

LandingFragment.kt 

package com.example.navigationgraphexample.fragment

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.navigation.findNavController
import com.example.navigationgraphexample.R
import com.example.navigationgraphexample.databinding.FragmentLandingBinding

class LandingFragment : Fragment() {

    lateinit var binding: FragmentLandingBinding
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment

        binding = DataBindingUtil.inflate(inflater,R.layout.fragment_landing, container, false)


        binding.btnLogin.setOnClickListener{
            it.findNavController().navigate(R.id.action_landingFragment2_to_loginFragment2)
        }
        binding.btnSignUp.setOnClickListener{
            it.findNavController().navigate(R.id.action_landingFragment2_to_signUpFragment3)
        }
        return binding.root


    }

}

2. Fragment LoginFragment Source code.

LoginFragment.

<?xml version="1.0" encoding="utf-8"?>
<layout
    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">
    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".fragment.SignUpFragment">

        <androidx.appcompat.widget.AppCompatButton

            android:id="@+id/btnGoToMain"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Go To Main Screen"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />



    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

LoginFragment.kt

package com.example.navigationgraphexample.fragment

import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.navigation.findNavController
import com.example.navigationgraphexample.R
import com.example.navigationgraphexample.databinding.FragmentLoginBinding


class LoginFragment : Fragment() {

    private lateinit var binding : FragmentLoginBinding
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_login, container, false)


        binding.btnGoToMain.setOnClickListener {
//            val intent = Intent(context,WelcomeActivity::class.java)
//            startActivity(intent)

            it.findNavController().navigate(R.id.action_loginFragment2_to_welcomeActivity)
            activity?.finish()
        }
        return binding.root
    }

}

 

2. Fragment SignUpFragment Source code.

SignUpFragment.xml

<?xml version="1.0" encoding="utf-8"?>
<layout
    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">
<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".fragment.SignUpFragment">

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/btnGoToMain"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Go To OTP Screen"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />



</androidx.constraintlayout.widget.ConstraintLayout>
</layout>

SignUpFragment.kt

package com.example.navigationgraphexample.fragment

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.navigation.findNavController
import com.example.navigationgraphexample.R
import com.example.navigationgraphexample.databinding.FragmentSignUpBinding


class SignUpFragment : Fragment() {
    private lateinit var binding : FragmentSignUpBinding
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_sign_up, container, false)

        binding.btnGoToMain.setOnClickListener {
            it.findNavController().navigate(R.id.action_signUpFragment_to_otpFragment)
        }

        return binding.root

    }



}

similar to add code to all fragment and run to text your App. source code on GitHub.

Read More Tutorial