👨‍💻
Sagar R. Kothari
  • README
  • _posts
    • 2019-08-13-Start-apache-server
    • Preview
    • 2020-02-12-SwiftUICardView
    • 2019-04-10-12-Swift5
    • 2021-07-11-Android-Basic-Setup
    • 2021-01-25-Android-Retrofit
    • 2020-02-05-BinaryTree-PostOrder-Traversal
    • 2020-02-06-Array-Rotation
    • 2019-04-12-14-JekyllGenerateCategoriesPage
    • 2020-09-28-nodejs
    • 2020-07-03-Android-Kotlin-Clickable-RecyclerView
    • 2021-01-24-Android-Kotlin-hideKeyboard
    • 2020-07-17-Android-NavigationComponent-SafeArgs
    • 2020-01-31-SinglyLinkList-RemoveThoseTotalZero
    • 2020-02-18-SwiftJustDayValue
    • 2021-05-29-Android-BottomSheet
    • 2020-02-05-BinaryTree-Search
    • 2020-02-03-FontForNumbersAndCurrency
    • 2020-07-01-Anroid-Kotlin-ListView
    • 2020-01-30-SinglyLinkList-Display
    • 2020-01-31-SinglyLinkList-Delete-Head
    • 2020-07-03-Anroid-Kotlin-RecyclerView
    • MainActivity.kt
    • 2021-05-29-Android-DropDown
    • Example 1
    • 2020-02-20-Swift-Form-Data-Request
    • 2020-01-31-SinglyLinkList-Delete-Before
    • 2020-02-19-UndoLastCommit
    • 2020-02-24-Swift-UIImagePickerController
    • Sample Fastlane Script to upload to fabric/crashlytics
    • 2021-02-09-Android-Switch
    • 2020-02-13-SwiftUI-ListViewWithSwipeDelete
    • 2020-07-05-Anroid-Kotlin-RecyclerView-Retrofit
    • 2021-01-25-Android-Configs
    • Convert SVG to png macOS command
    • build.gradle (Module: app)
    • 2020-07-15-Android-Kotlin-NavDrawer
    • 2020-02-05-BinaryTree-InOrder-Traversal
    • 2021-01-25-Android-NavPop
    • 2019-04-10-16-XcodeShortCuts
    • 2021-02-10-Android-Button-icon
    • 2019-08-12-CloudKit-DataSync
    • 2020-02-10-DSLinkListSwapNodes
    • 2020-02-18-SwiftDarkOrLightMode
    • 2020-02-02-Swift-Array-Chunked-Stride
    • 2020-02-16-OpenShareSheet
    • 2020-07-19-Android-NavigationComponent-NavDrawer
    • 2019-04-12-13-Swift-SHA256
    • 2020-07-18-Android-Share-Intent-Text
    • 2021-07-11-Android-Read-SMS
    • 2020-07-10-Anroid-RootCheck
    • Important Folder Locations for iOS App Developer
    • 2021-01-25-Android-Navigation-Animation
    • Sample Fastlane Script to upload to MS App Center
    • 2021-01-25-Android-UDID
    • 2020-07-14-FCM-ForeBack
    • 2019-04-10-18-TimezoneFromISO8601Date
    • 2020-01-31-SinglyLinkList-Delete-After
    • MainActivity.kt
    • 2019-04-12-11-DateTimeFormatterJekyll
    • 2020-07-01-Anroid-Kotlin-ListView-ImageDownload
    • 2020-01-31-SinglyLinkList-Delete-End
    • 2020-01-31-Fastlane-build-ios-simulator
    • 2019-04-10-19-Useful-tools
    • Pre-commit script for iOS projects for automated code review
    • How do I Validate email address?
    • 2019-04-12-15-SwiftDateExtension
    • 2020-02-05-BinaryTree-PreOrder-Traversal
    • 2020-02-05-BinaryTree-HeightOfTree
    • 2019-04-12-12-FormattingDoubleAsCurrency
    • 2020-02-05-BinaryTree-LevelOrder-Traversal
    • 2020-07-13-Anroid-KillApp
    • 2020-07-20-Android-Share-Intent-Image
    • 2020-02-15-AskForAppReview
    • 2019-04-12-10-TableViewHideSearchBar
    • 2020-02-18-SwiftSizeClass
    • Preview
    • 2020-02-05-BinaryTree-Insert
    • 2021-02-07-Android-Device-Lock
    • How do I show or hide password?
    • 2020-01-30-SinglyLinkList-Middle
    • 2020-07-16-Android-NavigationComponent
    • 2021-02-12-Android-Regex
    • 2020-01-31-SinglyLinkList-Insert-Before
    • 2021-02-10-Android-Button-Background
    • 2020-01-30-SinglyLinkList-Insert-atEnd
    • 2019-05-24-codeSnipsForVue
    • 2020-07-12-Anroid-EventBus
    • 2020-07-11-Anroid-Background-Foreground-Check
    • 2020-02-19-macOSCatalyst-AvoidPods
    • 2021-02-07-Android-Is-Internet-connected
    • 2020-02-07-SwiftUI-ImagePicker
    • 2020-02-04-Swift-IAP-Receipt-Validation
    • 2021-02-08-Android-hard-space
    • 2020-01-30-SinglyLinkList-Inverse
    • 2020-01-29-Swift-iCloud-check
    • 2021-01-24-Android-Kotlin-FragmentLayoutBinding
    • 2019-08-08-Pods-I-use
    • 2019-04-12-18-AddAcknowledgement
    • 2020-02-17-macOSCatalyst-HideTitleBar
    • 2019-04-12-16-isLive
    • 2020-07-02-Anroid-Kotlin-Volley-Get-GitUsers
    • 2019-04-13-11-SwiftRelativeDate
    • 2019-04-12-19-ChangeBarButtonFont
    • 2020-02-09-Swift-Equatable
    • 2021-02-13-Android-show-hide-menu
    • 2020-02-12-SwiftUI-List-withCardView
    • 2020-02-12-SwiftUIFabAction
    • 2019-08-08-zsh-git-commands
    • 2020-07-04-Anroid-Kotlin-RecyclerView-SwipeRefresh
    • 2020-01-30-PlayVideo
    • 2020-02-08-Swift-Reduce-Example
    • Generating App Icons from Single image named 1024x1024.png
    • Mocking data with Mocky and randomuser
    • 2020-02-14-Swift-PerformTaskInBackground
    • 2020-01-31-Github-Actions-Fastlane
    • 2020-02-25-Swift-UIImage-Resize
    • Preview
    • 2020-02-11-macOS-Mouse-Hover-Highlight
    • 2021-01-26-Android-Secure-Pref
    • 2020-02-07-SwiftUI-List-RemoveSeparator
    • 2020-01-30-SinglyLinkList-Insert-atHead
    • 2020-01-31-SinglyLinkList-Insert-After
    • 2020-01-31-SinglyLinkList-RemoveLoop
    • 2020-02-10-DSRecursionReverse
    • 2020-02-01-Swift-Reachability
    • 2021-02-11-Android-Copy-to-Clipboard
    • 2019-04-12-17-UsingCocoaLumberjack
    • 2020-02-07-SwiftUI-Pop-Navigation
    • 2020-07-05-Anroid-Kotlin-RecyclerView-ScrollToEnd
    • 2020-09-26-nodejs
    • 2020-07-03-Android-Kotlin-RecyclerView-PullToRefresh
    • Sample fastlane script to upload your app to TestFlight
  • tag
    • code
    • jekyll
    • customizations
    • analytics
    • installation
    • tags
    • images
    • comments
  • Tags
  • MyBookmarks
  • admin
  • Some info
Powered by GitBook
On this page
  • build.gradle (Project leve)
  • build.gradle (Module: app)
  • Step 1. Add fragments
  • Step 2. Add navigation Graph.
  • Step 2. Update activity_main.xml
  • Step 3. Update fragment_main.xml
  • Step 3. update MainFragment.kt as follows.
  • Step 4. Update fragment_detail.xml
  • Step 5. Update DetailFragment.kt

Was this helpful?

  1. _posts

2020-07-17-Android-NavigationComponent-SafeArgs

build.gradle (Project leve)

dependencies {
    ...
    classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.3.0"
    ...
}

build.gradle (Module: app)

    # MAKE SURE YOU DON'T MISS THIS
    apply plugin: "androidx.navigation.safeargs.kotlin"
    # AND THIS
    dependencies {
        ...
        implementation 'androidx.navigation:navigation-fragment-ktx:2.3.0'
        implementation 'androidx.navigation:navigation-ui-ktx:2.3.0'
        ...
    }
    # AND THIS
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    # AND THIS
    kotlinOptions {
        jvmTarget = JavaVersion.VERSION_1_8.toString()
    }

Step 1. Add fragments

  • Right click on package.

  • Add new fragment.

  • Blank fragment

  • Add MainFragment.kt & DetailFragment.kt

  • It would also create respective resource files

Step 2. Add navigation Graph.

  • Right click on res folder.

  • Add navigation/navigation.xml file.

  • Add both fragments created.

  • After adding those, it should look as follows.

<?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/navigation"
    app:startDestination="@id/mainFragment">

    <fragment
        android:id="@+id/mainFragment"
        android:name="com.sagar_r_kothari.navdemo.MainFragment"
        android:label="Main Fragment"
        tools:layout="@layout/fragment_main">
        <action
            android:id="@+id/action_mainFragment_to_detailFragment"
            app:destination="@id/detailFragment">
            <argument
                android:name="textContent"
                android:defaultValue="This is a default value to be passed to Add new entry fragment." />
        </action>
    </fragment>
    <fragment
        android:id="@+id/detailFragment"
        android:name="com.sagar_r_kothari.navdemo.DetailFragment"
        android:label="Detail Fragment"
        tools:layout="@layout/fragment_detail">
        <argument
            android:name="textContent"
            app:argType="string" />
    </fragment>
</navigation>

Step 2. Update activity_main.xml

<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">

    <!-- Following is important
    It adds a host fragment.
    It points to navigation graph.
    It also says that this is default host.
    Just copy & paste this. -->
    <fragment
        android:id="@+id/myNavHostFragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:navGraph="@navigation/navigation"
        app:defaultNavHost="true" />

</androidx.constraintlayout.widget.ConstraintLayout>

Step 3. Update fragment_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=".MainFragment">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:text="@string/hello_main_fragment"
        android:textAlignment="center"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/addEntryButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:text="@string/add_entry"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

</androidx.constraintlayout.widget.ConstraintLayout>

Step 3. update MainFragment.kt as follows.

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_main, container, false)
        view.addEntryButton.setOnClickListener {
            val testText = "This is my test text"
            // Access action & pass value
            val action = MainFragmentDirections.actionMainFragmentToDetailFragment(testText)
            requireView().findNavController().navigate(action)
        }
        return view
    }

Step 4. Update fragment_detail.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".DetailFragment">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/hello_blank_fragment" />

</FrameLayout>

Step 5. Update DetailFragment.kt

class DetailFragment : Fragment() {
    val args: AddNewEntryFragmentArgs by navArgs() // <<-- 1. arguments

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_add_new_entry, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        textView.text = args.textContent // <<-- 2. read from arguments
    }
}
Previous2021-01-24-Android-Kotlin-hideKeyboardNext2020-01-31-SinglyLinkList-RemoveThoseTotalZero

Last updated 4 years ago

Was this helpful?