반응형
안녕하세요. 오늘 알아볼건 Activity에서 Activity로 기본으로 지원하는 타입 값 이외에 다른 사용자 정의 타입값을 보내는 방법을 알아보겠습니다
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Parcelize | |
data class Question( | |
var answer_one : String, | |
var answer_two : String, | |
var answer_three : String, | |
var answer_four : String, | |
var answer_five : String, | |
var question : String, | |
var people : String | |
) : Parcelable |
data class에 @Parcelize 어노테이션을 추가해주고 자료형에 :Parcelable를 추가해 줍니다
이렇게 하고 Activity로 가서
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val intent = Intent(this, MainActivity::class.java) | |
intent.putExtra( | |
"question", | |
Question( | |
각각의 값에 맞는 값 매핑 | |
) | |
) | |
startActivity(intent) |
이렇게 넘겨줍니다
여기서 드는 궁금증이 하나 생깁니다
만약 배열형태의 사용자 정의 자료형은 어떻게 넘기지?? 정답은 쉽습니다!!
우선 앞에와 같이 data class에 @Parcelize 어노테이션을 추가해주고 자료형에 :Parcelable를 추가해 줍니다
그리고
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val array = mainViewModel.questionList | |
val intent = Intent(this, MainActivity::class.java) | |
intent.putParcelableArrayListExtra("questionList", array) | |
startActivity(intent) | |
finish() |
이런식으로 값을 넣어 넘겨줍니다
간단하죠?! 이제 다음은 다른 Activity에서 넘겨준 값을 받아볼 차례입니다
순서대로 받는 방법입니다
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//배열형태 | |
intent.getParcelableArrayListExtra<Question>("questionList") | |
//단일형태 | |
intent.getParcelableExtra<Question>("question") |
감사합니다
반응형
'Android' 카테고리의 다른 글
Android MVVM 패키지 구조 (0) | 2021.12.16 |
---|---|
Android Studio에서 Pytorch mobile을 사용하며 (4) | 2021.12.06 |
Android bottom navigation bar Text와 Icon 사이 margin (0) | 2021.11.12 |
Android Status Bar 투명처리 방법 (0) | 2021.11.11 |
Jetpack Compose에 대해 간단하게 알아보자! (0) | 2021.09.09 |