0
0
Android Kotlinmobile~20 mins

Navigation component setup in Android Kotlin - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Main Navigation Screen
This screen demonstrates setting up Android Navigation Component with two simple fragments and navigation between them using a button.
Target UI
---------------------
|    Main Screen     |
|                    |
|  [Go to Second]    |
---------------------

---------------------
|   Second Screen    |
|                    |
|  [Back to Main]    |
---------------------
Create two fragments: MainFragment and SecondFragment.
Set up Navigation Component with a NavHostFragment in the activity layout.
Add navigation graph XML with two destinations: MainFragment and SecondFragment.
Add a button in MainFragment to navigate to SecondFragment.
Add a button in SecondFragment to navigate back to MainFragment.
Starter Code
Android Kotlin
package com.example.navigationdemo

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // TODO: Setup NavHostFragment in activity_main.xml
    }
}

// TODO: Create MainFragment.kt and SecondFragment.kt with basic layouts and buttons
Task 1
Task 2
Task 3
Task 4
Solution
Android Kotlin
package com.example.navigationdemo

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

// MainFragment.kt
package com.example.navigationdemo

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.example.navigationdemo.databinding.FragmentMainBinding

class MainFragment : Fragment() {
    private var _binding: FragmentMainBinding? = null
    private val binding get() = _binding!!

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        _binding = FragmentMainBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.buttonGoSecond.setOnClickListener {
            findNavController().navigate(R.id.action_mainFragment_to_secondFragment)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}

// SecondFragment.kt
package com.example.navigationdemo

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.example.navigationdemo.databinding.FragmentSecondBinding

class SecondFragment : Fragment() {
    private var _binding: FragmentSecondBinding? = null
    private val binding get() = _binding!!

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        _binding = FragmentSecondBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.buttonBackMain.setOnClickListener {
            findNavController().navigate(R.id.action_secondFragment_to_mainFragment)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}

// activity_main.xml
<?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">

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:defaultNavHost="true"
        app:navGraph="@navigation/nav_graph"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

// nav_graph.xml
<?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"
    android:id="@+id/nav_graph"
    app:startDestination="@id/mainFragment">

    <fragment
        android:id="@+id/mainFragment"
        android:name="com.example.navigationdemo.MainFragment"
        android:label="Main Screen">
        <action
            android:id="@+id/action_mainFragment_to_secondFragment"
            app:destination="@id/secondFragment" />
    </fragment>

    <fragment
        android:id="@+id/secondFragment"
        android:name="com.example.navigationdemo.SecondFragment"
        android:label="Second Screen">
        <action
            android:id="@+id/action_secondFragment_to_mainFragment"
            app:destination="@id/mainFragment" />
    </fragment>

</navigation>

// fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp">

    <Button
        android:id="@+id/buttonGoSecond"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Go to Second" />

</FrameLayout>

// fragment_second.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp">

    <Button
        android:id="@+id/buttonBackMain"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Back to Main" />

</FrameLayout>

This solution sets up the Android Navigation Component with two fragments: MainFragment and SecondFragment.

The activity_main.xml contains a NavHostFragment which hosts the navigation graph defined in nav_graph.xml. This graph defines the two fragments and the actions to navigate between them.

Each fragment has a simple layout with a button. In MainFragment, the button navigates to SecondFragment using findNavController().navigate(). In SecondFragment, the button navigates back to MainFragment.

View binding is used for safe and easy access to views.

This setup follows Android best practices for navigation and keeps UI and navigation logic clean and simple.

Final Result
Completed Screen
---------------------
|    Main Screen     |
|                    |
|  [Go to Second]    |
---------------------

User taps 'Go to Second' button

---------------------
|   Second Screen    |
|                    |
|  [Back to Main]    |
---------------------

User taps 'Back to Main' button

Back to Main Screen
Tap 'Go to Second' button navigates to Second Screen.
Tap 'Back to Main' button navigates back to Main Screen.
Stretch Goal
Add a toolbar with a title that updates based on the current fragment.
💡 Hint
Use NavigationUI.setupActionBarWithNavController() in MainActivity and override onSupportNavigateUp() to handle back navigation.