-
[Android] [당근마켓 클론 코딩] 메인페이지에서 아이템 상세페이지로 data class 객체를 intent로 전달 (Parcelize)안드로이드 2024. 4. 18. 20:29
✏️ TIL(Today I Learned)
메인페이지에서 아이템을 클릭하면, 상세페이지로 이동과 동시에 아이템의 데이터를 전달하여 화면을 구성하도록 했다.
data class 객체를 intent로 전달하기 위해 Parcelize를 사용했다.
Parcelize는 Kotlin의 안드로이드 확장 라이브러리 중 하나로, 안드로이드에서 객체를 직렬화(Serialization)하고 전송하기 위해 사용된다.
이를 사용하기 위해서는, build.gradle(:app) 파일의 plugins에 id("kotlin-parcelize")를 추가해야한다.
plugins { alias(libs.plugins.androidApplication) alias(libs.plugins.jetbrainsKotlinAndroid) id ("kotlin-parcelize") // 추가 }
그후, data class에 @Parcelize 어노테이션을 달아준다.
@Parcelize data class MarketItem( val itemImage: Int, val itemTitle: String, val itemContent: String, val itemPrice: String, val userName: String, val userAddress: String, val itemChatCount: Int, var itemLikeCount: Int, var isLiked: Boolean, ) : Parcelable
이제 MarketItem객체는 Intent나 Bundle을 통해 전달할 수 있게 된 것이다.
또한, Parcelable을 구현할 때 발생할 수 있는 실수나 에러를 방지하여 안정성을 높이는 데 도움이 된다.MainActivity에서 MarketItem객체인 clickedItem를 putExtra()를 사용해 DetailActivity로 전달했다.
// MainActivity.kt adapter.itemClick = object : MarketAdapter.ItemClick { override fun onClick(view: View, position: Int) { val clickedItem = dataList[position] val intent = Intent(this@MainActivity, DetailActivity::class.java) intent.putExtra("clickedItem", clickedItem) startActivity(intent) } }
DetailActivity에서 이를 받아서, 화면에 나타내도록 했다.
val clickedItem = intent.getParcelableExtra<MarketItem>("clickedItem") clickedItem?.let { binding.ivDetailItem.setImageResource(it.itemImage) binding.tvDetailTitle.text = it.itemTitle binding.tvDetailContent.text = it.itemContent binding.tvDetailPrice.text = it.itemPrice binding.tvUserName.text = it.userName binding.tvUserAddress.text = it.userAddress isLiked = it.isLiked == true binding.ivLikeBtn.setImageResource( if (isLiked) {R.drawable.ic_like_full} else {R.drawable.ic_like_empty} ) }
'안드로이드' 카테고리의 다른 글
[Android] 주소록 App 만들기 - 기획 & 일정 (0) 2024.04.22 [Android] [당근마켓 클론 코딩] 메인페이지 구현3 - 커스텀 Floating Button (RecyclerView/ AlphaAnimation) (0) 2024.04.19 [Android] [당근마켓 클론 코딩] 메인페이지 구현2 - 키워드 알림 (Notification) (0) 2024.04.17 [Android] [당근마켓 클론 코딩] 메인페이지 구현1 (RecyclerView/ addItemDecoration()/ Spinner/ ArrayAdapter) (0) 2024.04.16 [Android] Fragment 데이터 전달 (0) 2024.04.11