android/Jetpack
5-1. Jetpack Navigation의 구성요소
android by kotlin
2022. 10. 9. 12:52
[1]. Jetpack Navigation 이란?
Jetpack Navigation 은 앱 내의 여러 컨텐츠에 들어갔다 나올 수 있게 하는 상호작용을 구현하도록 도와주는 라이브러리 이다.
[2]. Navigation 구성요소
1. Navigation Graph => 모든 Navigation 관련 정보가 모여있는 XML 파일이다. 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/a_fragment">
<fragment
android:id="@+id/a_fragment"
android:name=".presentation.view.AFragment"
android:label="a_fragment"
tools:layout="@layout/fragment_a">
<action
android:id="@+id/action_a_fragment_to_b_fragment"
app:destination="@id/b_fragment" />
</fragment>
<fragment
android:id="@+id/b_fragment"
android:name=".presentation.view.BFragment"
android:label="b_fragment"
tools:layout="@layout/fragment_b">
</fragment>
</navigation>
2. NavHost => Navigation Graph 를 호스팅하기 위한 빈 Container 이다.
<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=".presentation.view.MainActivity">
<androidx.fragment.app.FragmentContainerView
android:id="@+id/fragment_container_view"
android:layout_width="0dp"
android:layout_height="0dp"
<!-- 어떤 Navigation Graph 를 호스팅할 것인지 지정한다.-->
app:navGraph="@navigation/nav_graph"
<!-- 이 Fragment Container View 를 Navigation Graph 를 호스팅하는 View 로 지정한다. -->
app:defaultNavHost="true"
android:name="androidx.navigation.fragment.NavHostFragment"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
3. NavController => 사용자가 앱 내에서 이동할 때 Fragment 전환을 조정하는 객체이다. 즉 이 객체를 통해 Fragment 에서 다른 Fragment 로 전환을 요청할 수 있다.
class AFragment : Fragment() {
private var _binding: FragmentABinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentABinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initialize()
}
private fun initialize() {
initViews()
}
private fun initViews() {
binding.startBFragmentButton.setOnClickListener {
/*
Navigation Graph 에 정의한 Action ID 를 기반으로 생성된 메서드를 호출하여서 NavDirections 객체를 가져온 후
navController 에게 탐색을 요청한다.
*/
val action = AFragmentDirections.actionAFragmentToBFragment()
findNavController().navigate(action)
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}