适配器类,具有 DiffUtil 实现
class MyAdapter(private val context: Context, private val onItemClickListener:
(id:String)->Unit) :ListAdapter<SMS, MyAdapter.ViewHolder>(MyDiffCallback()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType:
Int):ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.list_view, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
when(holder) {
is ViewHolder -> {
holder.bind(getItem(position),context, onItemClickListener)
}
}
}
inner class ViewHolder(private val view: View) : RecyclerView.ViewHolder(view) {
private val msg = view.tvMsg
fun bind(
sms: SMS, context: Context,
onContactItemClickListener:(id:String)->Unit ) {
msg.text = sms.msgString
}
}
class MyDiffCallback : DiffUtil.ItemCallback<SMS>() {
override fun areItemsTheSame(oldItem: SMS, newItem: SMS): Boolean {
return oldItem.time == newItem.time
}
override fun areContentsTheSame(oldItem: SMS, newItem: SMS): Boolean {
return oldItem.time == newItem.time && oldItem.msgString == newItem.msgString
}
}
}
我将新列表/实时数据设置为适配器的活动中的 Oncreate() 方法
viewModel.data.observe(this, Observer { data->
data.let {
adapter.submitList(it)
}
}
问题是我必须滚动才能看到添加到列表中的新项目。我如何确保新项目在不滚动的情况下可见,就像我们在 whatsapp 聊天中看到的那样。