안드로이드
안드로이드 RecyclerView.ListAdapter 예제 in Kotlin
devGeek
2022. 1. 29. 11:29
반응형
개요
상품의 이미지, 이름 그리고 가격들을 리스트로 뿌려준다.
View Binding 을 사용한다.
실행 화면
프로젝트 구조
Code - Example
product_item.xml
layout\product_item.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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="wrap_content"
android:padding="15dp">
<ImageView
android:id="@+id/iv_thumbnail"
android:layout_width="150dp"
android:layout_height="150dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:src="@drawable/ic_launcher_background" />
<TextView
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:textColor="@color/black"
android:textSize="30sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="@id/iv_thumbnail"
app:layout_constraintStart_toEndOf="@id/iv_thumbnail"
app:layout_constraintTop_toTopOf="@id/iv_thumbnail"
tools:text="상품 이름" />
<TextView
android:id="@+id/tv_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/black"
android:textSize="17sp"
app:layout_constraintBottom_toBottomOf="@id/iv_thumbnail"
app:layout_constraintStart_toStartOf="@id/tv_title"
app:layout_constraintTop_toBottomOf="@id/tv_title"
tools:text="가격" />
</androidx.constraintlayout.widget.ConstraintLayout>
ProductModel.kt (DataClass)
data class ProductModel(
val id: Long,
var thumbnail: Drawable,
var title: String,
var price: String,
)
ProductAdapter.kt (ListAdapter)
class ProductAdapter : ListAdapter<ProductModel, ProductAdapter.ViewHolder>(diffUtil) {
inner class ViewHolder(var binding: ProductItemBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(item: ProductModel) {
binding.apply {
ivThumbnail.setImageDrawable(item.thumbnail)
tvTitle.text = item.title
tvPrice.text = item.price
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
ProductItemBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
// currentList: 해당 Adapter에 "submitList()"를 통해 삽입한 아이템 리스트
holder.bind(currentList[position])
}
companion object {
// diffUtil: currentList에 있는 각 아이템들을 비교하여 최신 상태를 유지하도록 한다.
val diffUtil = object : DiffUtil.ItemCallback<ProductModel>() {
override fun areItemsTheSame(oldItem: ProductModel, newItem: ProductModel): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: ProductModel, newItem: ProductModel): Boolean {
return oldItem == newItem
}
}
}
}
activity_main.xml
layout\activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">
<TextView
android:id="@+id/tv_title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:gravity="center"
android:text="RecyclerView.ListAdapter"
android:textColor="@color/black"
android:textSize="30sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="0dp"
android:layout_height="0dp"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/tv_title" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.kt
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val productAdapter = ProductAdapter()
binding.recyclerView.adapter = productAdapter
// productAdapter에 productModel 아이템 리스트 삽입
productAdapter.submitList(getProductItemList())
}
private fun getProductItemList(): ArrayList<ProductModel> {
var resultList = arrayListOf<ProductModel>()
var cnt = 0
while (cnt++ < 5) {
val id = System.currentTimeMillis()
val thumbnail = getDrawable(R.drawable.ic_launcher_background)
val title = "title_$cnt"
val price = "price_${cnt}원"
val product = ProductModel(id, thumbnail!!, title, price)
resultList.add(product)
}
return resultList
}
}
마무리하며...
- ListAdapter
- 리스트 어댑터는 백그라운드 스레드에서 기존 리스트와 새로 들어온 리스트 간 차이를 계산하여 RecyclerView에 데이터를 표시하기 위한 어댑터 기본 클래스이다.
- ListAdapter에서는 백 그라운드에서 아이템을 비교하고 업데이트 해주기 때문에 데이터를 삽입하거나 지울 때, RecyclerView.Adapter.NotifiyDataSetChanged()와 같은 명령어를 사용하지 않아 개발할 때 편리한 것 같다.
반응형