상세 컨텐츠

본문 제목

[안드로이드 코틀린] Navigation component part1 - 프래그먼트 쉽게 연결하는 방법

안드로이드

by aries574 2022. 12. 6. 23:37

본문


안녕하세요. 이번 시간에는 Navigation Component를 이용해서 메인 화면에 프래그먼트 쉽게 연결하는

방법에 대하여 알아보겠습니다.


목차

1. 실행 화면
2. 라이브러리 등록
3. 내비게이션 파일 만들기 my_nav.xml
4. 프래그먼트 생성
5. 내비게이션 파일에 프래그먼트 연결
6. 프래그먼트 설정
7. 메인 화면 구성 activity_main.xml


1. 실행 화면

 

2. 라이브러리 등록

build.gradle(Module:프로젝트명:app)

dependencies 괄호 안에 아래 코드를 넣어주시면 됩니다.

    implementation 'androidx.navigation:navigation-fragment-ktx:2.5.3'
    implementation 'androidx.navigation:navigation-ui-ktx:2.5.3'

 

3. 내비게이션 파일 만들기 my_nav.xml

res 선택 ->  마우스 오른쪽 클릭 -> new -> Android Resource File

파일 이름: my_nav

Resource type: Navigation

내비게이션 폴더 생성과 파일이 만들어 집니다.

 

4. 프래그먼트 생성

- 설명 

 1. 2개의 프래그먼트를 생성합니다.

 2. 파일명은 OneFragment, TwoFragment

 3. app 선택 -> New -> Fragment -> Fragment (Blank)

 

반응형

 

5. 내비게이션 파일에 프래그먼트 연결 my_nav.xml

 - 설명 

 1. 내비게이션 파일에 프래그먼트 등록해서 관리

 2. 액션태그 아이디를 통해 다른 프래그먼트 이동을 쉽게 할 수 있다.

 3. startDestination : 맨 처음 보여줄 프래그먼트 설정

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

    <fragment
        android:id="@+id/oneFragment"
        android:name="com.example.navigationcomponent.OneFragment"
        android:label="fragment_one"
        tools:layout="@layout/fragment_one" >
        <action
            android:id="@+id/action_oneFragment_to_twoFragment"
            app:destination="@id/twoFragment" />
    </fragment>
    <fragment
        android:id="@+id/twoFragment"
        android:name="com.example.navigationcomponent.TwoFragment"
        android:label="fragment_two"
        tools:layout="@layout/fragment_two" >
        <action
            android:id="@+id/action_twoFragment_to_oneFragment"
            app:destination="@id/oneFragment" />
    </fragment>
</navigation>


6. 프래그먼트 설정

fragment_one.xml

 - 설명 

 1. 프래그먼트 이동 기능 TextView

<?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=".OneFragment">
    
    <TextView
        android:id="@+id/one_text"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="30sp"
        android:gravity="center"
        android:text="One Fragment" />

</FrameLayout>

 

OneFragment.kt

 1. Navigation.findNavController(view).navigate

   - 프래그먼트간의 이동을 도와주는 함수

   - 내비게이션 파일에 등록한 액션 아이디를 인자 값으로 전달한다.

   - 액션 아이디에 해당하는 프래그먼트로 이동할 수 있다. 

class OneFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val view = inflater.inflate(R.layout.fragment_one, container, false)

        val oneText = view.findViewById<TextView>(R.id.one_text)

        //클릭 이벤트
        oneText.setOnClickListener {
            Navigation.findNavController(view).navigate(R.id.action_oneFragment_to_twoFragment)
        }

        return view
    }
}

 

 

fragment_two.xml

 - 설명

 1. 프래그먼트 이동 기능 TextView

<?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=".TwoFragment">
    
    <TextView
        android:id="@+id/two_text"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="30sp"
        android:gravity="center"
        android:text="Two Fragment" />

</FrameLayout>

 

TwoFragment.kt

 1. Navigation.findNavController(view).navigate

   - 프래그먼트간의 이동을 도와주는 함수

   - 내비게이션 파일에 등록한 액션 아이디를 인자 값으로 전달한다.

   - 액션 아이디에 해당하는 프래그먼트로 이동할 수 있다. 

class TwoFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val view = inflater.inflate(R.layout.fragment_two, container, false)

        val twoText = view.findViewById<TextView>(R.id.two_text)

        //클릭 이벤트
        twoText.setOnClickListener {
            Navigation.findNavController(view).navigate(R.id.action_twoFragment_to_oneFragment)
        }

        return view
    }
}

 

7. 메인 화면 구성 activity_main.xml

 - 설명 -

 1. 프래그먼트 화면을 보여주는 FragmentContainerView

 2. navGraph: 내비게이션 파일을 적용

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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" >

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/fragmentContainerView"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        app:defaultNavHost="true"
        app:navGraph="@navigation/my_nav" />
</LinearLayout>

2022.11.21 - [안드로이드] - [안드로이드 코틀린] 간단한 퀴즈 앱 만드는 방법 part1 - 메인화면 구성과 설정

 

[안드로이드 코틀린] 간단한 퀴즈 앱 만드는 방법 part1 - 메인화면 구성과 설정

안녕하세요. 이번 시간에는 퀴즈 앱 만들기 첫 번째 시간 - 메인화면 & 설정을 해보겠습니다. 목차 1. 실행 화면 2. 바인딩 설정 3. 문자 리소스 string.xml 4. 답변 drawable option_background.xml 5. 메인 화면

aries574.tistory.com

2022.11.07 - [안드로이드] - [안드로이드 코틀린] 파이어베이스 사용자 CRUD 만드는 방법 part1 - 프로젝트 생성

 

[안드로이드 코틀린] 파이어베이스 사용자 CRUD 만드는 방법 part1 - 프로젝트 생성

이번 시간에는 파이어베이스(Firebase) CRUD 만드는 방법 - 첫 번째 시간 안드로이드 스튜디오 프로젝트 생성, 파이어베이스 프로젝트 생성, 실시간 데이터베이스 생성 하는 방법에 대하여 알아보겠

aries574.tistory.com

2022.10.18 - [안드로이드] - [안드로이드 코틀린] 채팅앱 만드는 방법 part1 - 로그인 액티비티

 

[안드로이드 코틀린] 채팅앱 만드는 방법 part1 - 로그인 액티비티

이번 시간에는 채팅앱 만들기 첫 번째 시간 로그인 액티비티 만드는 방법을 알아보겠습니다. 목차 1. 실행 화면 2. 뷰 바인딩 3. 백그라운드 drawable 4. 로그인 화면 LogInActivity 5. 홈 화면 변경 1. 실

aries574.tistory.com

 

반응형

관련글 더보기

댓글 영역