ListAdapter 사용법

김흰돌·2023년 7월 17일
0

RecyclerView

목록 보기
3/4

ListAdapter란?

RecyclerView의 어댑터 인터페이스입니다. ListAdapter는 RecyclerView.Adapter를 상속받습니다.

기본적인 데이터 변경 관리를 쉽게 처리할 수 있는 특수한 유형의 어댑터입니다.

ListAdapter는 Diffutil 클래스와 결합하여 데이터 변경 사항을 비교하고 최소한의 업데이트만 수행하여 성능을 향상시킵니다.

ListAdapter를 사용하면 데이터의 변경 사항을 자동으로 감지하고 해당 변경 사항에 대한 업데이트를 수행할 수 있습니다.

이는 데이터 소스가 변경될 때마다 RecyclerView에 대한 전체 데이터 세트를 다시 설정하지 않고도 효율적인 업데이트를 수행할 수 있다는 장점이 있습니다.

ListAdapter는 이전 데이터와 새 데이터 간의 차이를 계산하여 새로운 항목을 삽입, 제거 도는 업데이트하고 애니메이션 효과를 적용할 수 있도록 도와줍니다.

ListAdapter에 사용되는 DiffUtil 클래스???

DiffUtil은 두 개의 리스트 또는 데이터 세트 간의 차이를 계산하고, 새로운 항목이나 변경된 항목을 식별하는 데 사용됩니다.

이를 통해 RecyclerView의 업데이트 작업을 최적화하고 성능을 향상시킬 수 있습니다.

DiffUtil 클래스를 사용한 RecyclerViewAdapter 예제

DiffUtilCallback.kt

class DiffUtilCallback(
    private val oldList: MutableList<Item>,
    private val newList: MutableList<Item>
    ): DiffUtil.Callback() {
    
    override fun getOldListSize(): Int = oldList.size
    override fun getNewListSize(): Int = newList.size

    override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int) =
        oldList[oldItemPosition].id == newList[newItemPosition].id

    override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int) =
        oldList[oldItemPosition] == newList[newItemPosition]

}

위와 같이 Diffutil 클래스를 생성합니다.

RecyclerViewAdapter.kt

class RecyclerViewAdapter() :
    RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder>() {

    private val itemList = mutableListOf<Item>()

    fun updateList(items: MutableList<Item>) {
        val diffCallback = DiffUtilCallback(itemList, items)
        val diffResult = DiffUtil.calculateDiff(diffCallback)

        itemList.clear()
        itemList.addAll(items)

        diffResult.dispatchUpdatesTo(this)
    }

중략....

updateList 메서드는 새로운 데이터 세트를 전달받고, DiffUtil을 사용하여 이전 데이터 세트와의 차이를 계산합니다.

그 다음 결과를 어댑터에 적용하여 데이터를 갱신합니다.

areItemsTheSame() 메서드는 항목의 고유 식별자를 비교하고, areContentsTheSame() 메서드는 항목의 내용이 동일한지 비교합니다.

차이 계산이 완료되면, RecyclerView는 변경 사항을 적용하고 화면을 업데이트합니다.

이를 통해 Diffutil을 사용하여 이전 데이터와 새 데이터 사이의 변경 사항만을 감지하고 적용하므로 성능이 향상되며RecyclerView의 업데이트 작업을 효율적으로 처리할 수 있습니다.

ListAdapter 예제

DiffUtil 클래스를 따로 만들 필요 없이 ListAdapter를 상속받습니다.

class RecyclerViewAdapter() : ListAdapter<Item, RecyclerViewAdapter.MyViewHolder>(diffUtil) {

    class MyViewHolder(private val binding: ItemBinding) :  RecyclerView.ViewHolder(binding.root) {
        val root = binding.root

        fun bind(item: Item) {
            binding.data = item
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val binding: ItemBinding = ItemBinding.inflate(LayoutInflater.from(parent.context))
        return MyViewHolder(binding, listener)
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        holder.bind(currentList[position])
    }

    companion object {

        val diffUtil = object : DiffUtil.ItemCallback<Item>() {

            override fun areItemsTheSame(
                oldItem: Item,
                newItem: Item
            ): Boolean {
                return (oldItem.hospUrl == newItem.hospUrl)
            }

            override fun areContentsTheSame(
                oldItem: Item,
                newItem: Item
            ): Boolean {
                return oldItem == newItem
            }

        }
    }
}

ListAdapter를 상속받고 아이템의 차이를 계산하는 companion object를 만듭니다.

ListAdapter를 사용하면 데이터의 변경을 자동으로 감지하고 업데이트할 수 있으므로, getItem() 및 getItemCount 메서드를 구현할 필요가 없습니다.

데이터 변경은 DiffUtil과 ItemCallback을 통해 자동으로 처리됩니다.

0개의 댓글