I haven’t written my blog for a long time. Recently, I have a lot of work to do and I have no state. Today, I suddenly use a funny thing to record it

Finish the effect drawing today




⚠️: My data is initialized like this:

demand

  • You can implement positive ordering by ID, as well as reverse ordering
  • Add/add multiple are also added by ID
  • Add overwrites previous data if it is repeated
  • Delete deletes the element in position 0

use

The bean class

data class SortBean(val id: Int, // subscript val title: String, // abbreviation of val title: String)
Copy the code

SortListCallBack SortedListAdapterCallback abstract class rewrite the three methods

class SortListCallBack(adapter: RecyclerView.Adapter<*>) : 
	SortedListAdapterCallback<SortBean>(adapter) {
    /* * TODO is used to sort sort conditions * * Returns 0 if the specified number is equal to the argument. * Returns a negative value if it is less than any other value; * Returns a positive number if it is greater than any other value. * /
    override fun compare(o1: SortBean, o2: SortBean): Int = let {
        // From large to small
        // o2.position.compareTo(o1.position)
        // From small to big
        o1.id.compareTo(o2.id)
    }

    /* * * Argument one: oldItem - The previous representation of the object. Parameter two: newItem - A new object that replaces the previous object. Returns: True if the items are the same; False if the project contents are different. * * /
    override fun areContentsTheSame(oldItem: SortBean, newItem: SortBean): Boolean =
        oldItem.hashCode() == newItem.hashCode()
  

    /* * Author: Android Super soldier * Time: 2021/10/909:53 *TODO:*/
    override fun areItemsTheSame(item1: SortBean, item2: SortBean): Boolean = 
        item1.id == item2.id
}
Copy the code

Here is the essence of sorting, and a key explanation of the three methods:

  • Compare (o1: SortBean, O2: SortBean): Int

For example, the current sort is by ID.

You can also sort by id from largest to smallest!

You can also sort them alphabetically

  • AreItemsTheSame (Item1: SortBean, Item2: SortBean): Boolean is used to de-weight

Directly look at the effect at a glance:

  • areContentsTheSame(oldItem: SortBean, newItem: SortBean): Boolean. If you have the same property it goes to this method

You think that’s the end of it? Let’s look at another situation!

RecyclerView code

The rest of the code is simple and should make sense if you look around

	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);
        // Initialize the data randomly
        sortBeans.add(new SortBean(2."Sichuan"."AS"));
        sortBeans.add(new SortBean(11.Inner Mongolia."N"));
        sortBeans.add(new SortBean(5."Hubei"."H"));
        sortBeans.add(new SortBean(2."Shanxi"."S"));
        sortBeans.add(new SortBean(3."Shaanxi"."S"));
        sortBeans.add(new SortBean(5."Hunan"."H"));
// sortbeans.add (new SortBean(10, "", "H"));
//        sortBeans.add(new SortBean(12, "浙江", "Z"));

        // Set the data
        sortAdapter.sortList = sortBeans;

        recyclerView.setAdapter(sortAdapter);
Copy the code

The difference between RecyclerView and normal RecyclerView is that when you set up your data, you might have used ArrayList before, but now you use SortedList, and there’s nothing different!

Adapter classes

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(a): Int = sortList.size()

    /* * Author: Android Super soldier * Time: 2021/10/913:12 *TODO:Add all collections */
    fun addAll(list: List<SortBean>) {
        sortList.beginBatchedUpdates()

        sortList.addAll(list)

        sortList.endBatchedUpdates()
    }

    /* * Author: Android Super soldier * Time: 2021/10/913:11 *TODO:Add an element */
    fun setData(sortBean: SortBean) {
        sortList.add(sortBean)
    }

    /* * Author: Android Super soldier * Time: 2021/10/913:11 *TODO:Remove an element */ based on the subscript
    fun deleteData(index: Int) {
        sortList.removeItemAt(index)
    }

    /* * Author: Android Super soldier * Time: 2021/10/913:11 *TODO:Deletes an object in the collection */
    fun deleteData(data: SortBean) {
        sortList.remove(data)
    }
}
Copy the code

Note:

  • SortedList is not a subclass of List, nor is it a method provided in Java
  • SortedList is unique to Android
  • Its internal storage is stored in arrays
  • SortedList currently only supports RecyclerView, not ListView

Finally, there are some button click events:

Initialize 26 letters and random numbers

 Random mRandom = new Random();
 
ArrayList<Character> charList = new ArrayList<>();
for (int i = 0; i < 26; i++) {
    charList.add((char) (65 + i));
}
Copy the code

Click events:

  // TODO adds one
        viewDataBinding.btAdd.setOnClickListener(v -> {
                    / / random
                    int charRandom = mRandom.nextInt(charList.size());
                    sortAdapter.setData(new SortBean(charRandom, "add-"+ charRandom, String.valueOf(charList.get(charRandom)))); });// TODO adds 5
        viewDataBinding.btAddAll.setOnClickListener(v -> {
            ArrayList<SortBean> list = new ArrayList<>();
            for (int i = 0; i < 5; i++) {
                / / random
                int charRandom = mRandom.nextInt(charList.size());

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

        / / delete TODO
        viewDataBinding.btDelete.setOnClickListener(v -> {
            // Always delete the data at position 0
            sortAdapter.deleteData(0);
        });
Copy the code

The complete code

Original is not easy, your praise is the biggest support for me!