DiffUtil 优雅替代RecyclerView 刷新(二)A
2021-09-07 本文已影响0人
没有了遇见
DiffUtil 用于计算两个列表之间的差异并输出将第一个列表转换为第二个列表的更新操作列表,它可用于计算 RecyclerView 适配器的更新.
官方简介语法
Diffutil处理数据耗时出现原先:
DiffUtil 同步方案处理大量数据的时候耗时较长衍生出异步方案
解决方案:
AsyncListDiffer 在后台通过 DiffUtil 计算两个列表之间的差异的助手
主要方案: 异步刷新
主要对象:AsyncListDiffer<UserInfo>(this,RecyclerViewDiffItemCallBack()),DiffUtil.ItemCallback()
1:AsyncListDiffer():在后台通过 DiffUtil 计算两个列表之间的差异的助手
2:DiffUtil.ItemCallback() :新旧数据处理的监听
方法
class AsyncListDifferAdapter(mContext: Context) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
var mContext: Context? = null
var diff: AsyncListDiffer<UserInfo>? = null
init {
this.mContext = mContext
diff=AsyncListDiffer<UserInfo>(this,RecyclerViewDiffItemCallBack())
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
var binding = DataBindingUtil.inflate<ItemMainOneBinding>(
LayoutInflater.from(mContext),
R.layout.item_main_one,
parent,
false
)
var holder = KtDataBindingViewHolder(binding.root)
holder.binding = binding
return holder
}
fun setDatas(newList: List<UserInfo>) {
if(diff==null)return
diff!!.submitList(newList)
}
/**
* @param payloads A non-null list of merged payloads. Can be empty list if requires full
* update.
*/
override fun onBindViewHolder(
holder: RecyclerView.ViewHolder,
position: Int,
payloads: MutableList<Any>
) {
// payloads 为null 整条数据刷新
if (payloads.isEmpty() || payloads.size <= 0) {
super.onBindViewHolder(holder, position, payloads)
} else {
//局部更新 不会更新整个item 更新指定的控件
var bundle = payloads.get(0) as Bundle
if (bundle != null) {
var name = bundle.getString("name")
var phoneNum = bundle.getString("phoneNum")
var holder = holder as KtDataBindingViewHolder
var binding = holder.binding as ItemMainOneBinding
if (!TextUtils.isEmpty(name)) {
binding.tvName.text = name
}
if (!TextUtils.isEmpty(phoneNum)) {
binding.tvPhone.text = phoneNum
}
}
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
Log.e("绘制:", "" + position)
var holder = holder as KtDataBindingViewHolder
var binding = holder.binding as ItemMainOneBinding
binding.tvName.setText(getItem(position)!!.name)
binding.tvPhone.setText(getItem(position)!!.phoneNum)
}
fun getItem(position: Int): UserInfo {
return diff!!.currentList.get(position)
}
fun getItems():List<UserInfo>{
return diff!!.currentList
}
override fun getItemCount(): Int {
return diff!!.currentList.size
}
}
调用:
private fun setNewData() {
var userList = ArrayList<UserInfo>()
for (index in 0..10) {
var userInfo = UserInfo()
if (index == 0) {
userInfo.name = "开始"
} else if (index == 10) {
userInfo.name = "结束"
} else {
userInfo.name = "测试" + index
}
userInfo.id = index
userInfo.phoneNum = "1853853738" + index
userList.add(userInfo)
}
mAdapter!!.setDatas(userList)
}