DiffUtil 用于計算兩個列表之間的差異并輸出將第一個列表轉(zhuǎn)換為第二個列表的更新操作列表,它可用于計算 RecyclerView 適配器的更新.
官方簡介語法
出現(xiàn)原先:
DiffUtil 同步方案處理大量數(shù)據(jù)的時候耗時較長衍生出異步方案
解決方案:
AsyncListDiffer 在后臺通過 DiffUtil 計算兩個列表之間的差異的助手
主要方案: 異步刷新
主要對象:AsyncListDiffer<UserInfo>(this,RecyclerViewDiffItemCallBack()),DiffUtil.ItemCallback()
1:AsyncListDiffer():在后臺通過 DiffUtil 計算兩個列表之間的差異的助手
2:DiffUtil.ItemCallback() :新舊數(shù)據(jù)處理的監(jiān)聽
方法
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 整條數(shù)據(jù)刷新
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
}
}
調(diào)用:
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 = "結(jié)束"
} else {
userInfo.name = "測試" + index
}
userInfo.id = index
userInfo.phoneNum = "1853853738" + index
userList.add(userInfo)
}
mAdapter!!.setDatas(userList)
}