두 프래그먼트 간 이동하기

최대환·2024년 1월 2일
0

1. Fragment 2개를 생성

먼저, 두 개의 프래그먼트를 생성합니다. 이 예제에서는 각 프래그먼트에 텍스트를 추가하여 구분하겠습니다.

2. 네비게이션 리소스 파일을 생성

네비게이션을 구현하기 위해 네비게이션 리소스 파일을 생성합니다.

3. mainActivity layout에서 NavHostFragment를 추가

MainActivity의 레이아웃 XML에서 NavHostFragment를 추가합니다. 이 NavHostFragment는 네비게이션 그래프를 호스팅하며, 프래그먼트 전환을 담당합니다.

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/fragmentContainerView"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/nav_test"
        tools:layout_editor_absoluteX="1dp"
        tools:layout_editor_absoluteY="1dp" />

</androidx.constraintlayout.widget.ConstraintLayout>

4. 네비게이션 그래프 연결

네비게이션 그래프를 연결합니다. 이렇게 하면 'action' 태그가 생성됩니다.

5. 다른 fragment로 이동하는 코드 작성

프래그먼트에서 버튼을 누르면 다른 프래그먼트로 이동하도록 코드를 작성합니다.

override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment

        val view = inflater.inflate(R.layout.fragment_blank1, container, false)

        view.findViewById<Button>(R.id.btn1).setOnClickListener {
            Navigation.findNavController(view).navigate(R.id.action_blankFragment1_to_blankFragment2)
        }

        return view
    }

이와 같이 코드를 작성하면, 버튼을 클릭하면 다른 프래그먼트로 네비게이션됩니다. 반대 방향으로의 네비게이션도 같은 방식으로 구현할 수 있습니다.

profile
나의 개발지식 output 공간

0개의 댓글