【问题标题】:Randomize LiveData<List<names>随机化 LiveData<List<names>
【发布时间】:2020-02-20 09:34:51
【问题描述】:

如何在ViewModel 中随机化LiveData&lt;list&lt;StudentEntity&gt;&gt; 并在我的RecyclerView 中显示结果?我在想我可以做一个

Collection.shuffle(Arrays.asList(myList))

但我认为这不会改变 LiveDatalist 中对象的顺序。

我的片段

....
public void RandomizeListOrder() {
    mMainActivityViewModel.setRandomOrder();
    adapter.notifyDataSetChanged();
}

视图模型

private LiveData<List<StudentEntity>> mStudentList

public void setRandomOrder() {
    Collection.shuffle(Arrays.asList(mStudentList));
}

【问题讨论】:

    标签: java android random android-livedata


    【解决方案1】:

    您可以使用实时数据转换来操作实时数据。

    val transformedLiveData = Transformations.map(
                    yourActualLiveData) { //Shuffle logic here }
    

    【讨论】:

      【解决方案2】:

      如果您对 Kotlin 解决方案感兴趣,您可以这样做:

      val mStudentList = MutableLiveData<List<StudentEntity>>()
      
      fun setRandomOrder() {
          mStudentList.value?.let { students ->
              mStudentList.value = students.shuffled()
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-10
        • 2012-04-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-02
        • 1970-01-01
        • 2019-04-08
        相关资源
        最近更新 更多