상세 컨텐츠

본문 제목

[안드로이드 코틀린] Navigation component part4 - 프래그먼트 간에 데이터 쉽게 보내는 방법

안드로이드

by aries574 2022. 12. 9. 22:03

본문


안녕하세요. 이번 시간에는 Navigation Component를 이용해서 프래그먼트 간에 데이터를 쉽게

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

이전 포스팅은 아래 링크를 들어가시면 볼 수 있습니다.

2022.12.08 - [안드로이드] - [안드로이드 코틀린] Navigation component part3 - BottomNavigaion 쉽게 만드는 방법

 

[안드로이드 코틀린] Navigation component part3 - BottomNavigaion 쉽게 만드는 방법

안녕하세요. 이번 시간에는 Navigation Component를 이용해서 BottomNavigaion 쉽게 만드는 방법에 대하여 알아보겠습니다. 이전 포스팅은 아래 링크를 들어가시면 볼 수 있습니다. 2022.12.07 - [안드로이드]

aries574.tistory.com


목차

1. 실행 화면
2. 라이브러리 등록
3. 내비게이션 파일 만들기
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'

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

id 'androidx.navigation.safeargs.kotlin'

build.gradle(Project:프로젝트명)

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

id 'androidx.navigation.safeargs' version '2.5.3' apply false

 

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

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

파일 이름: my_nav

Resource type: Navigation

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

 

4. 프래그먼트 생성

- 설명

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

 2. 파일명은 FirstFragment, SecondFragment

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

 

반응형


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

- 설명 - 

 1. action

   이동할 프래그먼트 설정

 2. argument

   넘겨받을 값 설정

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

    <fragment
        android:id="@+id/firstFragment"
        android:name="com.example.navigationexam.FirstFragment"
        android:label="fragment_first"
        tools:layout="@layout/fragment_first" >
        <action
            android:id="@+id/first_to_second"
            app:destination="@id/secondFragment" />
    </fragment>
    <fragment
        android:id="@+id/secondFragment"
        android:name="com.example.navigationexam.SecondFragment"
        android:label="fragment_second"
        tools:layout="@layout/fragment_second" >
        <argument
            android:name="argsValue"
            app:argType="string" />
    </fragment>
</navigation>

 

6. 프래그먼트 설정

 

fragment_first.xml

 - 설명 - 

 1. 전송할 텍스트 입력할 EditText

 2. 텍스트 전송하는 Button

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

    <EditText
        android:id="@+id/args_name_edit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="이름"
        android:textSize="40sp" />

    <EditText
        android:id="@+id/args_age_edit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/args_name_edit"
        android:hint="나이"
        android:textSize="40sp" />

    <Button
        android:id="@+id/send_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/args_age_edit"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="40dp"
        android:text="전송"
        android:textSize="30sp" />
</RelativeLayout>

 

FirstFragment.kt

 - 설명 - 

 1. FirstFragmentDirections

   - navigation.safeargs 플러그인 추가하면 생기는 클래스

   - 프래그먼트 이름 + Directions

 2. firstToSecond

   프래그먼트 액션 아이디

 3. findNavController().navigate

   프래그먼트 이동하는 기능

class FirstFragment : Fragment() {

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

        val argsEdit = view.findViewById<EditText>(R.id.args_edit)
        val sendBtn = view.findViewById<Button>(R.id.send_btn)

        sendBtn.setOnClickListener {
            //입력값
            val sendArgs = argsEdit.text.toString()

            val action = FirstFragmentDirections.firstToSecond(sendArgs)

            findNavController().navigate(action)
        }

        return view
    }

}

 

fragment_second.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=".SecondFragment">


    <TextView
        android:id="@+id/args_text"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textSize="40sp"
        android:textStyle="bold" />

</FrameLayout>

 

SecondFragment.kt

- 설명 - 

 1. args: SecondFragmentArgs by navArgs()

   전송 받은 데이터 꺼내오는 객체

 2. argsValue

   내비게이션 파일에 추가한 argument name

class SecondFragment : Fragment() {

    private val args: SecondFragmentArgs by navArgs()

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

        val argsText = view.findViewById<TextView>(R.id.args_text)

        argsText.text = args.argsValue

        return view
    }
}

 

7. 메인 화면 구성

 activity_main.xml

- 설명 -

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

<?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:id="@+id/drawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    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"
        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.10.18 - [안드로이드] - [안드로이드 코틀린] 채팅앱 만드는 방법 part1 - 로그인 액티비티

 

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

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

aries574.tistory.com

 

2022.10.06 - [안드로이드] - [안드로이드 코틀린] tic-tac-toe 보드게임 만드는 방법 part1 - 뷰 바인딩 및 화면구성

 

[안드로이드 코틀린] tic-tac-toe 보드게임 만드는 방법 part1 - 뷰 바인딩 및 화면구성

이번 시간에는 Tic Tac Toe 보드 게임의 화면 구성을 해보겠습니다. Tic Tac Toe 게임은 오목처럼 번갈아 가며 클릭을 해서 누가 먼저 한 줄을 만들면 이기는 단순한 게임입니다. 목차 1. 실행 화면 2.

aries574.tistory.com

 

반응형

관련글 더보기

댓글 영역