本文介绍了如何改组RealmResults对象的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个RealmResults对象,该对象保存.where.findAll()查询的输出.我正在RecyclerView中显示此对象的内容,但是由于RealmResults对象的内容是静态的,因此每次打开RecyclerView时,它都会显示相同的记录集.我想随机播放(随机化)RealmResults的内容,以便可以在RecyclerView中显示RealmResults中的不同值.请提出一些我可以执行相同操作的可能方法.

I have a RealmResults object which holds output of a .where.findAll() query. I am showing contents of this object in a RecyclerView, but since the contents of the RealmResults object are static, it shows same set of records evertime the RecyclerView is opened. I want to shuffle (randomize) the contents of RealmResults so that I can show different values that are in the RealmResults in my RecyclerView. Please suggest some possible ways in which I can perform the same.

推荐答案

您不应该对列表本身进行随机化,而应该对列表(索引)的访问进行随机化.

You should not randomize the list itself, you should randomize your access of it (the indices).

构建一个包含[0, n-1]

List<Integer> indices = new ArrayList<>(realmResults.size());
for(int i = 0; i < realmResults.size(); i++) {
    indices.add(i);
}

随机播放

Collections.shuffle(indices);

然后,当您选择视图持有者数据时,将为具有索引的随机位置的索引域结果

Then when you pick the view holder data, index realm results with indexed random position

public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    if(holder instanceof YourHolder) {
        YourHolder yourHolder = (YourHolder) holder;
        RealmData realmData = realmResults.get(indices.get(position));
        //init data for your holder
    }
}

这篇关于如何改组RealmResults对象的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 18:10