簡體   English   中英

隨機化 LiveData <list<names></list<names>

[英]Randomize LiveData<List<names>

如何在ViewModel中隨機化LiveData<list<StudentEntity>>並在我的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));
}

您可以使用實時數據轉換來操作實時數據。

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

好吧,如果您對 Kotlin 解決方案感興趣,您可以這樣做:

val mStudentList = MutableLiveData<List<StudentEntity>>()

fun setRandomOrder() {
    mStudentList.value?.let { students ->
        mStudentList.value = students.shuffled()
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM