여러가지 데이터 전달 방법이 있는 상황에서 데이터 전달의 한 방법이라고 보시면 될 것 같습니다.
1. 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"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/nav_graph"
app:startDestination="@id/FirstFragment">
<fragment
android:id="@+id/FirstFragment"
android:name="com.project.safeargs.FirstFragment"
android:label="@string/hello_blank_fragment"
tools:layout="@layout/fragment_first">
<action
android:id="@+id/action_FirstFragment_to_SecondFragment"
app:destination="@id/SecondFragment" />
</fragment>
<fragment
android:id="@+id/SecondFragment"
android:name="com.project.safeargs.SecondFragment"
android:label="@string/hello_blank_fragment"
tools:layout="@layout/fragment_second">
<action
android:id="@+id/action_SecondFragment_to_FirstFragment"
app:destination="@id/FirstFragment" />
<argument
android:name="item"
app:argType="com.project.safeargs.Item[]" />
</fragment>
</navigation>
쪽 코드를 보시면 Item[]이라고 타입을 지정해주는 것을 확인할 수 있습니다. 타입은 Item 객체의 배열 타입이 됩니다.
2. FirstFragment.kt
class FirstFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_first, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val item = ArrayList<Item>()
item.add(Item(111, "changed"))
view.findViewById<Button>(R.id.button_first).setOnClickListener {
val action = FirstFragmentDirections.actionFirstFragmentToSecondFragment(item.toTypedArray())
findNavController().navigate(action)
}
}
}
3. SecondFragment.kt
class SecondFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_second, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val args: SecondFragmentArgs by navArgs()
val itemList = args.item.toCollection(ArrayList())
view.findViewById<TextView>(R.id.textview_second).text = "${itemList[0].id} ${itemList[0].name}"
view.findViewById<Button>(R.id.button_second).setOnClickListener {
findNavController().navigate(R.id.action_SecondFragment_to_FirstFragment)
}
}
}
val args: SecondFragmentArgs by navArgs() 를 통해서 xml 작성된 argument 에 대한 클래스가 자동으로 생성이 되고, 받아 오게 됩니다.
safe args는 네이게이션 AAC를 사용할 때 프레그먼트와 데이터 전송까지 한번에 관리하게 용의한 방법으로 볼 수 있습니다.
https://developer.android.com/guide/navigation/navigation-pass-data?hl=ko