[英]Randomize LiveData<List<names>
How can I randomize a LiveData<list<StudentEntity>>
in a ViewModel
and display the results in my RecyclerView
?如何在ViewModel
中随机化LiveData<list<StudentEntity>>
并在我的RecyclerView
中显示结果? I was thinking I could do a我在想我可以做一个
Collection.shuffle(Arrays.asList(myList))
but I don't believe this changes the order of the objects in the LiveDatalist.但我不相信这会改变 LiveDatalist 中对象的顺序。
MyFragment我的片段
....
public void RandomizeListOrder() {
mMainActivityViewModel.setRandomOrder();
adapter.notifyDataSetChanged();
}
ViewModel视图模型
private LiveData<List<StudentEntity>> mStudentList
public void setRandomOrder() {
Collection.shuffle(Arrays.asList(mStudentList));
}
You can manipulate livedata using livedata transformations.您可以使用实时数据转换来操作实时数据。
val transformedLiveData = Transformations.map(
yourActualLiveData) { //Shuffle logic here }
Well if you are interested in Kotlin solution you could do it like this:好吧,如果您对 Kotlin 解决方案感兴趣,您可以这样做:
val mStudentList = MutableLiveData<List<StudentEntity>>()
fun setRandomOrder() {
mStudentList.value?.let { students ->
mStudentList.value = students.shuffled()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.