android 实用的小技巧(RecyclerView 数据排序 -- SortedList)

好久没写博客了,最近工作事情比较多,没有状态,今天忽然用到一个好玩的东西,拿来记录一下下~~

今日完成效果图


⚠️: 我的数据是这么初始化的: 在这里插入图片描述

需求

  • 可以根据id来实现正序,以及倒叙排序
  • 添加/添加多个 也根据id来添加
  • 添加若重复 则覆盖之前的数据
  • 删除时候删除第0个位置的元素

使用

bean类

data class SortBean(
    val id: Int, // 下标
    val title: String, // 名字
    val abbreviation: String, // 简称
)
复制代码

SortListCallBack类 实现SortedListAdapterCallback 抽象类重写三个方法

class SortListCallBack(adapter: RecyclerView.Adapter<*>) : 
	SortedListAdapterCallback<SortBean>(adapter) {
    /*
     * TODO 用来排序 排序条件
     *
     *        如果指定的数与参数相等返回0。
     *        如果小于其他值,则返回负数;
     *        如果大于其他值,则返回正数。
     */
    override fun compare(o1: SortBean, o2: SortBean): Int = let {
        // 从大到小
        // o2.position.compareTo(o1.position)
        // 从小到大
        o1.id.compareTo(o2.id)
    }

    /*

     *
     *  参数一: oldItem–对象的上一个表示形式。
        参数二: newItem–替换上一个对象的新对象。
        返回:如果项目内容相同,则为True;如果项目内容不同,则为false。
        *
     */
    override fun areContentsTheSame(oldItem: SortBean, newItem: SortBean): Boolean =
        oldItem.hashCode() == newItem.hashCode()
  

    /*
     * 作者: android 超级兵
     * 时间: 2021/10/9 09:53
     * TODO: [用来去重]
     */
    override fun areItemsTheSame(item1: SortBean, item2: SortBean): Boolean = 
        item1.id == item2.id
}
复制代码

这里是排序的精髓,关键的解释一下这三个方法:

  • compare(o1: SortBean, o2: SortBean): Int [设置排序条件]

比如当前是根据id排序[从小到大]

在这里插入图片描述

也可以根据id从大到小排序!

在这里插入图片描述

当然也可以根据字母顺序进行排序

在这里插入图片描述

  • areItemsTheSame(item1: SortBean, item2: SortBean): Boolean 用来去重

直接看效果图一目了然: 在这里插入图片描述

  • areContentsTheSame(oldItem: SortBean, newItem: SortBean): Boolean. 如果有相同的属性就会走到这个方法

在这里插入图片描述

以为这么就完了吗? 再来看一种情况!

在这里插入图片描述

RecyclerView 的代码

其余代码都简单,大致看看应该就能懂

	RecyclerView recyclerView = findViewById(R.id.recyclerView);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        SortAdapter sortAdapter = new SortAdapter();

        SortListCallBack callBack = new SortListCallBack(sortAdapter);

        SortedList<SortBean> sortBeans = new SortedList<>(SortBean.class, callBack);
        // 随便初始化一下数据
        sortBeans.add(new SortBean(2, "四川", "AS"));
        sortBeans.add(new SortBean(11, "内蒙古", "N"));
        sortBeans.add(new SortBean(5, "湖北", "H"));
        sortBeans.add(new SortBean(2, "山西", "S"));
        sortBeans.add(new SortBean(3, "陕西", "S"));
        sortBeans.add(new SortBean(5, "湖南", "H"));
//        sortBeans.add(new SortBean(10, "海南", "H"));
//        sortBeans.add(new SortBean(12, "浙江", "Z"));

        // 设置数据
        sortAdapter.sortList = sortBeans;

        recyclerView.setAdapter(sortAdapter);
复制代码

和普通的RecyclerView不一样的地方就是设置数据的时候 之前可能用的是ArrayList 现在使用的是SortedList 其余的没有什么不一样的地方!

Adapter类

class SortAdapter : RecyclerView.Adapter<SortAdapter.SortViewHolder>() {

    lateinit var sortList: SortedList<SortBean>

    inner class SortViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SortViewHolder {
        return SortViewHolder(View.inflate(parent.context, R.layout.item, null))
    }

    override fun onBindViewHolder(holder: SortViewHolder, position: Int) {
        holder.itemView.tv.text = sortList[position].toString()
    }

    override fun getItemCount(): Int = sortList.size()

    /*
     * 作者: android 超级兵
     * 时间: 2021/10/9 13:12
     * TODO: 添加所有集合
     */
    fun addAll(list: List<SortBean>) {
        sortList.beginBatchedUpdates()

        sortList.addAll(list)

        sortList.endBatchedUpdates()
    }

    /*
     * 作者: android 超级兵
     * 时间: 2021/10/9 13:11
     * TODO: 添加一个元素
     */
    fun setData(sortBean: SortBean) {
        sortList.add(sortBean)
    }

    /*
     * 作者: android 超级兵
     * 时间: 2021/10/9 13:11
     * TODO: 根据下标删除某个元素
     */
    fun deleteData(index: Int) {
        sortList.removeItemAt(index)
    }

    /*
     * 作者: android 超级兵
     * 时间: 2021/10/9 13:11
     * TODO: 删除集合中的某个对象
     */
    fun deleteData(data: SortBean) {
        sortList.remove(data)
    }
}
复制代码

注意点:

  • SortedList 并不是List的子类,也不是java中提供的方法
  • SortedList 是 android中独有的类
  • 其内部存储是通过数组来存储
  • SortedList 目前仅支持配合RecyclerView使用,还不支持ListView

最后还有一些按钮的点击事件:

初始化26个字母与随机数

 Random mRandom = new Random();
 
ArrayList<Character> charList = new ArrayList<>();
for (int i = 0; i < 26; i++) {
    charList.add((char) (65 + i));
}
复制代码

点击事件:

  // TODO 添加一个
        viewDataBinding.btAdd.setOnClickListener(v -> {
                    // 随机
                    int charRandom = mRandom.nextInt(charList.size());
                    sortAdapter.setData(new SortBean(charRandom, "add-" + charRandom, String.valueOf(charList.get(charRandom))));
                }
        );

        // TODO 添加5个
        viewDataBinding.btAddAll.setOnClickListener(v -> {
            ArrayList<SortBean> list = new ArrayList<>();
            for (int i = 0; i < 5; i++) {
                // 随机
                int charRandom = mRandom.nextInt(charList.size());

                list.add(new SortBean(charRandom, "all-" + charRandom, String.valueOf(charList.get(charRandom))));
            }
            sortAdapter.addAll(list);
        });

        // TODO 删除
        viewDataBinding.btDelete.setOnClickListener(v -> {
            // 始终删除第0个位置的数据
            sortAdapter.deleteData(0);
        });
复制代码

完整代码

原创不易,您的点赞就是对我最大的支持!

猜你喜欢

转载自juejin.im/post/7016960186355023886