简体   繁体   中英

How can I update the position of an item inside of a RecyclerView?

I'm trying to add a feature to a To-Do list that causes a "checked" item to go to the bottom of the the list. I'm using an ArrayList to hold the items which are organized using a RecyclerView so I know that key will be to update the position but I'm not sure how to do that.

I'm confused how you'd move everything up by one and then put the checked item in the last position so that it's at the bottom of the list.

This is how I'm doing the checking and unchecking of the boxes:

taskCheckBox.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v) {
                if (holder.taskCheckBox.isChecked())
                {
                    bucketItem.setSelected(false);
                    holder.taskCheckBox.setChecked(false);
                }
                else
                {
                    bucketItem.setSelected(true);
                    holder.taskCheckBox.setChecked(true);
                }
            }
        });

I don't know what I'd add to update the position and I'm still confused by how I always know what the "bottom" is because there isn't a fixed number of item in the list.

Android team added a support for this kind of actions. Check out DiffUtils: https://github.com/mrmike/DiffUtil-sample

In a nutshell, you only need to provide a proper data set, and let the library figure out what changed.

If you still want to do this manually, you'll need to do something like this:

  1. On click, update the underlying model to have proper selected state

  2. Reorder that item to a proper place in a list. (list.remove(position) and then list.add(item) perhaps)

  3. Call notifyDataSetChanged() on your adapter. (or even better notifyRangeChanged(from, to)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM