Android recyclerview 实现单选,多选,反选等小功能。(建议直接翻到最下面克隆源码)
单选关键代码
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val fruit = fruitList[position]
if (fruit.isChecked) {
holder.binding.check.setImageResource(R.drawable.checked)
} else {
holder.binding.check.setImageResource(R.drawable.unchecked)
}
holder.binding.fruitImage.setImageResource(fruit.imageId)
holder.binding.fruitName.text = fruit.name
holder.binding.root.setOnClickListener {
mOnItemClickListener?.onItemClick(position)
if (checkPos != position) {
//取消上一个位置的勾选状态
fruitList[checkPos].isChecked = false
notifyItemChanged(checkPos)
//设置新的勾选状态
checkPos = holder.bindingAdapterPosition
fruitList[checkPos].isChecked = true
notifyItemChanged(checkPos)
}
}
}
多选关键代码
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val fruit = fruitList[position]
if (fruit.isChecked) {
holder.binding.check.setImageResource(R.drawable.checked)
} else {
holder.binding.check.setImageResource(R.drawable.unchecked)
}
holder.binding.fruitImage.setImageResource(fruit.imageId)
holder.binding.fruitName.text = fruit.name
holder.binding.root.setOnClickListener {
if (fruitList[position].isChecked) {
fruit.isChecked = false
notifyItemChanged(position)
} else {
fruit.isChecked = true
notifyItemChanged(position)
}
checkList.clear()
fruitList.forEach {
if (it.isChecked) {
checkList.add(it)
}
}
}
mOnItemClickListener?.onItemClick(position, checkList)
}
实现反选的关键代码
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val fruit = fruitList[position]
if (fruit.isChecked) {
holder.binding.check.setImageResource(R.drawable.checked)
} else {
holder.binding.check.setImageResource(R.drawable.unchecked)
}
holder.binding.fruitImage.setImageResource(fruit.imageId)
holder.binding.fruitName.text = fruit.name
holder.binding.root.setOnClickListener {
if (fruitList[position].isChecked) {
fruit.isChecked = false
notifyItemChanged(position)
} else {
fruit.isChecked = true
notifyItemChanged(position)
}
checkList.clear()
fruitList.forEach {
if (it.isChecked) {
checkList.add(it)
}
}
}
mOnItemClickListener?.onItemClick(position, checkList)
}
/**
* 反选方法
*
* @return List<Fruit> 返回返选后的集合
*/
fun setInvertSelection(): List<Fruit> {
val newList = ArrayList<Fruit>()
fruitList.forEach {
if (!it.isChecked) {
newList.add(it)
}
}
fruitList.forEach {
it.isChecked = !it.isChecked
}
notifyDataSetChanged()
return newList
}
/**
* 清除所有所选
*/
fun setClear() {
fruitList.forEach {
if (it.isChecked) {
it.isChecked = false
}
}
notifyDataSetChanged()
}
- 编写语言:kotlin(什么?不会kotlin?学吧kotlin yyds!)
- 实现的方法其实有很多种,自己觉得这个更简单粗暴点吧(就是自己菜不会优化)
- 可能对超级新手或者学习recyclerview的同学有点用吧。
- 有其他实现方式的大佬可以在评论区贴出你的地址大家一起学习进步
- 觉得有用的同学可以点个赞或者评论个yyds
- 这种小功能百度上一堆抄袭的自己试都不试直接转载或者贴个下载地址让你付费下载的真的是ex!
- 直接贴源码⬇️⬇️⬇️ 如果你上不了github评论区讲下,我传gitee
- GITHUB