Study Record

[안드로이드] RecyclerView ListAdapter 살펴보기 본문

안드로이드

[안드로이드] RecyclerView ListAdapter 살펴보기

초코초코초코 2023. 8. 10. 18:55
728x90

 

😶 ListAdapter 개요

데이터 목록을 보여줄 때 주로 사용되는 View 는 RecyclerView 이다. 그 중 데이터를 관리하는 adapter 는 일반적으로 정적 데이터 목록을 표시한다. 데이터 리스트가 정의되면 목록을 보여준다. 나중에 데이터가 변경되고 데이터를 다시 정의해주면, 새로운 데이터 리스트 전체 목록이 업데이트될 것이다. 

 

데이터 하나가 변할 때마다 전체 리스트 목록이 새로 고침되는 것은 데이터가 실시간으로 변동되는 환경(ex. 데이터베이스)에 적합하지 않다. (앱의 지속성 측면에서 충분하지 않다.)

 

데이터가 동적으로 변경되는 점을 고려한 기술로 ListAdapter 가 있다. ListAdapter 는 AsyncListDiffer 를 사용하여 이전 데이터 목록과 새 데이터 목록 간의 차이를 고려하여 목록이 업데이트된다. 데이터베이스가 포함된 프로그램과 같이 데이터가 자주 업데이트되는 환경에서는 ListAdapter 를 사용하는 것이 성능이 더 우수하다.

 

 

Adapter 를 정의하는 예시 코드이다. ListAdapter<T, VH> 에서 T 는 항목 데이터의 데이터 타입을 명시하고 VH 는 ViewHolder 를 의미한다. ListAdapter 의 생성자로 받는 diffCallback  은 두 가지 함수를 재정의해야 하는데 areItemsTheSame() 메서드는 같은 두 항목이 동일한지에 대한 여부를 결정하기 위한 메서드이며,

areContentsTheSame() 메서드는 두 항목의 데이터가 동일한지 확인할 때 호출되는 메서드이다.

class PhotoGridAdapter : ListAdapter<MarsPhoto,
        PhotoGridAdapter.MarsPhotoViewHolder>(DiffCallback) {

    companion object DiffCallback : DiffUtil.ItemCallback<MarsPhoto>() {
        override fun areItemsTheSame(oldItem: MarsPhoto, newItem: MarsPhoto): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: MarsPhoto, newItem: MarsPhoto): Boolean {
            return oldItem.imgSrcUrl == newItem.imgSrcUrl
        }

    }

    class MarsPhotoViewHolder(
        private var binding: GridViewItemBinding
    ) : RecyclerView.ViewHolder(binding.root) {

        fun bind(MarsPhoto: MarsPhoto) {
            binding.photo = MarsPhoto
            binding.executePendingBindings()
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int)
    : PhotoGridAdapter.MarsPhotoViewHolder {
        return MarsPhotoViewHolder(GridViewItemBinding.inflate(
            LayoutInflater.from(parent.context)))
    }

    override fun onBindViewHolder(holder: PhotoGridAdapter.MarsPhotoViewHolder, position: Int) {
        val marsPhoto = getItem(position)
        holder.bind(marsPhoto)
    }
}

 

List 의 항목에 대한 데이터를 업데이트하러면 다음과 같이 submitList() 메서드를 호출한다.

val data : List<MarsPhoto> = listOf()
(binding.recyclerView.adapter as PhotoGridAdapter).submitList(data)

 

 

 

 

ListAdapter  |  Android Developers

androidx.appsearch.builtintypes.properties

developer.android.com

 

728x90