본문 바로가기

컴퓨터 공학/Android

RecyclerView Adapter의 확장버전 ListAdapter 예시

Android Docs에 따르면

It is RecyclerView.Adapter base class for presenting List data in a RecyclerView, including computing diffs between Lists on a background thread.

백그라운드 스레드에서 리스트간의 차이를 계산해주는 RecyclerView.Adapter를 바탕으로 하는 클래스이다.

class HomeMemoAdapter: ListAdapter<Memo, HomeMemoAdapter.HomeMemoViewHolder>(object : DiffUtil.ItemCallback<Memo>(){
    override fun areItemsTheSame(oldItem: Memo, newItem: Memo):
            Boolean = oldItem == newItem

    override fun areContentsTheSame(oldItem: Memo, newItem: Memo):
            Boolean = oldItem == newItem
}) {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HomeMemoViewHolder {
        val binding: ItemHomeMemoBinding =
            ItemHomeMemoBinding.inflate(LayoutInflater.from(parent.context), parent, false)

        return HomeMemoViewHolder(binding)
    }

    override fun onBindViewHolder(holder: HomeMemoViewHolder, position: Int) {
        holder.bindTo(getItem(position))
    }

    inner class HomeMemoViewHolder(binding: ItemHomeMemoBinding) : RecyclerView.ViewHolder(binding.getRoot()) {
        val binding : ItemHomeMemoBinding = binding

        fun bindTo(memo: Memo){
            // TODO :: BIND MEMO
            binding.tvContent.text = memo.content
        }
    }
}