以往使用 RecyclerView 時,您需要使用 RecyclerView。Adapter 可顯示靜態資料清單。儘管特別適用於 Bus Schedule 等應用程式,但使用資料庫時,往往遇到的都是即時處理資料的變更。即使只有一個項目的內容有變更,系統仍會重新整理整個回收器的檢視畫面。但對大多數使用持續性的應用程式來說,這種做法並不夠。
動態變更清單的替代方案稱為 ListAdapter。ListAdapter 使用 AsyncListDiffer 來判斷舊資料清單和新資料清單之間的差異。之後,系統再根據這兩份清單之間的差異來更新回收器檢視畫面。因此,處理頻繁更新的資料時,回收器檢視畫面的執行效能會較高,就像在資料庫應用程式中經常遇到的情況一樣。
例子 :
class BusStopAdapter(private val onItemClicked: (Schedule) -> Unit) : ListAdapter<Schedule, BusStopAdapter.BusStopViewHolder>(DiffCallback) {
class BusStopViewHolder(private var binding: BusStopItemBinding): RecyclerView.ViewHolder(binding.root) {
@SuppressLint("SimpleDateFormat")
fun bind(schedule: Schedule) {
binding.stopNameTextView.text = schedule.stopName
binding.arrivalTimeTextView.text = SimpleDateFormat("h:mm a").format(
Date(schedule.arrivalTime.toLong() * 1000)
)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BusStopViewHolder {
val viewHolder = BusStopViewHolder(
BusStopItemBinding.inflate(
LayoutInflater.from( parent.context),
parent,
false
)
)
viewHolder.itemView.setOnClickListener {
val position = viewHolder.adapterPosition
onItemClicked(getItem(position))
}
return viewHolder
}
override fun onBindViewHolder(holder: BusStopViewHolder, position: Int) {
holder.bind(getItem(position))
}
companion object {
private val DiffCallback = object : DiffUtil.ItemCallback<Schedule>() {
override fun areItemsTheSame(oldItem: Schedule, newItem: Schedule): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Schedule, newItem: Schedule): Boolean {
return oldItem == newItem
}
}
}
}
0 comments:
張貼留言