Kotlin
复制代码
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import java.util.UUID
import kotlin.random.Random
const val ITEM_COUNT = 30
class MainActivity : AppCompatActivity() {
private var mAdapter: MyAdapter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val rv = findViewById<RecyclerView>(R.id.rv)
val layoutManager = GridLayoutManager(this, 3)
rv.layoutManager = layoutManager
mAdapter = MyAdapter()
rv.adapter = mAdapter
}
override fun onResume() {
super.onResume()
val newList = mutableListOf<MyItem>()
for (i in 0 until ITEM_COUNT) {
val item = MyItem()
item.pos = i
item.change = Random.Default.nextBoolean()
item.data = System.currentTimeMillis()
item.contentId = UUID.randomUUID()
newList.add(item)
}
mAdapter?.onChange(newList)
}
class MyAdapter : RecyclerView.Adapter<MyVH> {
private val mDiffer = AsyncListDiffer(this, object : DiffUtil.ItemCallback<MyItem>() {
override fun areItemsTheSame(oldItem: MyItem, newItem: MyItem): Boolean {
return oldItem.pos == newItem.pos
}
override fun areContentsTheSame(oldItem: MyItem, newItem: MyItem): Boolean {
return oldItem.contentId == newItem.contentId
}
override fun getChangePayload(oldItem: MyItem, newItem: MyItem): Any? {
return super.getChangePayload(oldItem, newItem)
}
})
constructor() {
val list = mutableListOf<MyItem>()
for (i in 0 until ITEM_COUNT) {
val item = MyItem(i)
item.data = 0L
item.change = false
list.add(item)
}
onChange(list)
}
fun onChange(list: MutableList<MyItem>) {
mDiffer.submitList(list)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyVH {
val view = LayoutInflater.from(parent.context).inflate(android.R.layout.simple_list_item_2, parent, false)
return MyVH(view)
}
override fun getItemCount(): Int {
return mDiffer.currentList.size
}
override fun onBindViewHolder(holder: MyVH, position: Int) {
holder.text1.text = "pos=${mDiffer.currentList[position].pos}"
holder.text2.text = "data=${mDiffer.currentList[position].data}"
if (mDiffer.currentList[position].change) {
holder.text1.setTextColor(Color.RED)
holder.text2.setTextColor(Color.RED)
} else {
holder.text1.setTextColor(Color.BLACK)
holder.text2.setTextColor(Color.BLACK)
}
}
}
class MyVH(itemView: View) : RecyclerView.ViewHolder(itemView) {
val text1: TextView = itemView.findViewById(android.R.id.text1)
val text2: TextView = itemView.findViewById(android.R.id.text2)
}
class MyItem {
var pos = 0
var data = 0L
var contentId = UUID.randomUUID()
var change = false
constructor(pos: Int) {
this.pos = pos
}
constructor() : this(0) {
}
}
}