【问题标题】:How to change position of item in Recycler View如何在回收站视图中更改项目的位置
【发布时间】:2018-10-16 10:54:26
【问题描述】:

我正在开发一个具有回收站视图的 Android 应用程序。我在回收站视图中随机订购了一些物品。我想将列表的第五项移动到第一个位置。并将之前在第一个位置的项目移动到第二个位置。有人可以帮我吗?

【问题讨论】:

    标签: android android-recyclerview


    【解决方案1】:

    您可以使用Collections.swap()

    • Swaps 指定列表中指定位置的元素。 (如果指定的位置相等,则调用此方法会使列表保持不变。)

    方法

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

    参数:

    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.
    

    示例代码

    // 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);
    

    【讨论】:

    • 你知道如何保存那个位置吗,因为我已经完成了Collections.swap() 这工作,但是当应用程序关闭并再次打开时不会保存位置。
    • 当用户在某处关闭应用程序时,您需要保存该位置,然后当用户打开使用该保存位置时,您需要保存该位置
    • 我们如何保存您回答的那个位置?
    • @Spritzig 你想如何保存位置以及你想保存哪个位置
    • 我会在 SO 中添加一个问题并通知您。
    【解决方案2】:

    RecyclerView 的工作方式是每次屏幕上出现新项目时,它都会调用您的自定义 RecyclerView.Adapter 子类。适配器有一个数据集的引用,您从中获取视图数据,并通过 ViewHolder(项目的布局)和索引到 onBindViewHolder(MyViewHolder holder, int position) 以获取 dataset[position] 并将数据放入 holder.textview.setText(dataset[position])

    因此,要交换元素的位置,您有 2 个选项:

    • 重新排列初始数据集中的数据。有可能它是某种类型的 ArrayList,而您这样做 TEMP=dataset[5];ArrayList.remove(TEMP);ArrayList.insert(TEMP,1); ArrayList 会根据需要移动所有内容。

    • 如果保持数据集完好无损很重要,您可以重写适配器,以便它保留{ position : dataset_index } 的映射并根据该映射填充项目。这应该是微不足道的。

    然后你必须用adapter.notifyDataSetChaged();刷新数据

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-08
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-17
      • 1970-01-01
      • 2021-12-30
      相关资源
      最近更新 更多