Development record of developer who study hard everyday.

,

How to use safe args of navigation in android

 How to use safe args of navigation in android

android blog

1. Add dependency in build.gradle file(project level)

repositories {
google()
jcenter()
maven {url "https://maven.google.com"}
}
dependencies {

//navigation
classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.8.0"

}


2. Add plugin

plugins {
id 'dagger.hilt.android.plugin'
}


3. Add argument's attribute in navigation graph which is xml file

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

<fragment
android:id="@+id/homeFragment"
android:name="org.techtown.volleyball.fragments.HomeFragment"
android:label="HomeFragment" >

<action
android:id="@+id/action_homeFragment_to_teamNewsFragment"
app:destination="@id/teamNewsFragment" >
            <!-- add argument tag in action tag -->
<argument
android:name="newsUrl"
app:argType="string"
android:defaultValue=""
/>
</action>


</fragment>

<fragment
android:id="@+id/teamNewsFragment"
android:name="org.techtown.volleyball.fragments.TeamNewsFragment"
android:label="TeamNewsFragment">
        <!--Add argument tag in destination fragment-->
<argument
android:name="newsUrl"
app:argType="string"
android:defaultValue=""
/>

</fragment>

</navigation>


4. Navigate with argument

val action = HomeFragmentDirections.actionHomeFragmentToTeamNewsFragment(link)
findNavController().navigate(action)


5. Receive argument in destination fragment.

class TeamNewsFragment : BaseFragment<FragmentTeamNewsBinding>(){
override val layoutResID: Int
get() = R.layout.fragment_team_news
private val args : TeamNewsFragmentArgs by navArgs()

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
Log.d(TAG, "onViewCreated")


binding.webView.loadUrl(args.newsUrl)
}



}

We can receive argument with "by navArgs()" which fragment-ktx library provides.






Share:

댓글 없음:

댓글 쓰기