상세 컨텐츠

본문 제목

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

안드로이드

by aries574 2022. 12. 19. 13:29

본문


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

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

이전 포스팅을 수정해서 만들었습니다.

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

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

 

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

안녕하세요. 이번 시간에는 Navigation Component를 이용해서 프래그먼트 간의 데이터를 쉽게 보내는 방법에 대하여 알아보겠습니다. 이전 포스팅은 아래 링크를 들어가시면 볼 수 있습니다. 2022.12.08

aries574.tistory.com


목차

1. 실행 화면
2. 라이브러리 등록
3. 사용자 클래스 만들기
4. 내비게이션 설정
5. 프래그먼트 설정


1. 실행 화면

 

2. 라이브러리 등록

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

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

id 'kotlin-parcelize'


3. 사용자 클래스 만들기

- 설명 -

 1. name : 이름

 2. age: 나이

@Parcelize
data class User(

    val name: String,
    val age: String
): Parcelable

 

반응형


4. 내비게이션 설정

- 설명 -

 1. argument name: 인자 값 불러오기 위한 이름

 2. argument argType: 클래스 위치

<?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="user"
            app:argType="com.example.navigationexam.User" />
    </fragment>
</navigation>

 

5. 프래그먼트 설정

 

fragment_first.xml

- 설명 -

 1. 이름 입력 EditText

 2. 나이 입력 EditText

 3. 전송 기능 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. User(name, age)

   User 생성자에 데이터 등록

 2. firstToSecond(user)

   user 객체 전송

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 argsNameEdit = view.findViewById<EditText>(R.id.args_name_edit)
        val argsAgeEdit = view.findViewById<EditText>(R.id.args_age_edit)

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

        sendBtn.setOnClickListener {
            //입력값

            val name = argsNameEdit.text.toString()
            val age = argsAgeEdit.text.toString()

            val user = User(name, age)

            val action = FirstFragmentDirections.firstToSecond(user)

            findNavController().navigate(action)
        }

        return view
    }

}

 

SecondFragment.kt

- 설명 -

 1. args.user.name

   내비게이션 파일에 등록된 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)

        val name = args.user.name
        val age = args.user.age

        argsText.text = "이름: $name 나이: $age"

        return view
    }
}

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.09.28 - [안드로이드] - [안드로이드 코틀린] HTTP 통신 Retrofit2 사용법 part1 - 권한 및 설정

 

[안드로이드 코틀린] HTTP 통신 Retrofit2 사용법 part1 - 권한 및 설정

Retrofit2 라이브러리를 이용해서 HTTP 통신을 하는 방법을 알아보겠습니다. 이번 시간에는 권한 및 설정을 하겠습니다. 목차 1. 권한 등록 2. 라이브러리 등록 3. 모델 클래스 4. 서비스 인터페이스 1.

aries574.tistory.com

 

반응형

관련글 더보기

댓글 영역