AsyncListDiffer实际上是DifferUtil+Async,对DifferUtil进行了封装,实现数据比较时在异步线程,任务完成自动切换到主线程更新UI;
对AsyncListDiffer的使用可以直接参考或者继承androidx.recyclerview.widget.ListAdapter
,里面直接做了这部分工作,将更新后的数据集合直接submit就可以了;
原理,很简单
private static class MainThreadExecutor implements Executor {
final Handler mHandler = new Handler(Looper.getMainLooper());
MainThreadExecutor() {}
@Override
public void execute(@NonNull Runnable command) {
mHandler.post(command);
}
}
public AsyncDifferConfig<T> build() {
if (mBackgroundThreadExecutor == null) {
synchronized (sExecutorLock) {
if (sDiffExecutor == null) {
sDiffExecutor = Executors.newFixedThreadPool(2);
}
}
mBackgroundThreadExecutor = sDiffExecutor;
}
return new AsyncDifferConfig<>(
mMainThreadExecutor,
mBackgroundThreadExecutor,
mDiffCallback);
}
示例
class RecyclerViewAdapter(diffCallback: ItemCallback<User>) : ListAdapter<User, UserViewHolder>(diffCallback) {
constructor() : this(object : ItemCallback<User>() {
override fun areItemsTheSame(oldItem: User, newItem: User): Boolean {
return oldItem == newItem
}
override fun areContentsTheSame(oldItem: User, newItem: User): Boolean {
return oldItem.name == newItem.name
}
})
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder {
return UserViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.adapter_item_recyclerview, parent, false))
}
override fun onBindViewHolder(holder: UserViewHolder, position: Int) {
holder.itemView.tv_text.text = getItem(position).toString()
holder.itemView.setOnClickListener { v -> Toast.makeText(v.context, "点击:$position", Toast.LENGTH_SHORT).show() }
}
}
网友评论