简体   繁体   English

如何在回收站视图中更改项目的位置

[英]How to change position of item in Recycler View

I am working on an Android app which has a recycler view.我正在开发具有回收站视图的 Android 应用程序。 I have items ordered randomly in the recycler view.我在回收商视图中随机订购了物品。 I want to move the fifth item of the list to the first position.我想将列表的第五项移动到第一个位置。 And move the item previously at the first position to second position.并将之前在第一个位置的项目移动到第二个位置。 Can anybody help me with this please?有人可以帮我吗?

You can use Collections.swap()您可以使用Collections.swap()

  • Swaps the elements at the specified positions in the specified list. Swaps指定列表中指定位置的元素。 (If the specified positions are equal, invoking this method leaves the list unchanged.) (如果指定的位置相等,则调用此方法会使列表保持不变。)

METHOD方法

 public static void swap(List<?> list,
        int i,
        int j)

Parameters:参数:

list - The list in which to swap elements.
i - the index of one element to be swapped.
j - the index of the other element to be swapped.

SAMPLE CODE示例代码

// first swap the item using  Collections.swap() method
Collections.swap(yourList, firstPosition, positionToSwap);

// than notify your adapter about change in list using  notifyItemMoved() method
YourAdapter.notifyItemMoved(firstPosition, positionToSwap);

The way RecyclerView works is every time a new item comes on screen it calls your custom RecyclerView.Adapter subclass. RecyclerView工作方式是每次屏幕上出现新项目时,它都会调用您的自定义RecyclerView.Adapter子类。 Adapter has a reference for the dataset you take data for views from and gets passed the ViewHolder (the layout of an item) and index into onBindViewHolder(MyViewHolder holder, int position) to take dataset[position] and put the data into holder.textview.setText(dataset[position]) . Adapter 有一个数据集的参考,你从中获取数据用于视图并通过ViewHolder (项目的布局)和索引到onBindViewHolder(MyViewHolder holder, int position)以获取dataset[position]并将数据放入holder.textview.setText(dataset[position])

As such, to swap places of elements you have 2 options:因此,要交换元素的位置,您有两个选择:

  • rearrange data in the initial dataset.重新排列初始数据集中的数据。 Chances are it's an ArrayList<> of some kind and you do TEMP=dataset[5];ArrayList.remove(TEMP);ArrayList.insert(TEMP,1);有可能它是某种 ArrayList<> 并且您执行TEMP=dataset[5];ArrayList.remove(TEMP);ArrayList.insert(TEMP,1); ArrayList will shift everything as required. ArrayList 将根据需要移动所有内容。

  • if it is important to keep dataset intact, you can rewrite your adapter, so that it keeps a map of { position : dataset_index } and populates items according to that map.如果保持数据集完整很重要,您可以重写您的适配器,以便它保留{ position : dataset_index }的地图并根据该地图填充项目。 That should be trivial.那应该是微不足道的。

And then you have to refresh the data with adapter.notifyDataSetChaged();然后你必须用adapter.notifyDataSetChaged();刷新数据adapter.notifyDataSetChaged();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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