随机播放ArrayList

时间:2018-11-19 18:46:20

标签: java android collections android-recyclerview shuffle

我有两个RecyclerView和一个ArrayList,叫做 collections ,我正在尝试改编ArrayList并得到12项。

@Override
protected void onPostExecute(List<CollectionsModel> collections) {
    super.onPostExecute(collections);
    if (isAdded() && getActivity() != null) {
        setAdapterForRecyclerView(collections);
         setAdapterForRecyclerViewBestCollections(shuffleCollection(collections));
    }
}

随机播放方法:

public List<CollectionsModel> shuffleCollection(List<CollectionsModel> collectionsModelList) {
    java.util.Collections.shuffle(collectionsModelList);
    return collectionsModelList;
}

RecyclerView 1的适配器方法:

private void setAdapterForRecyclerViewBestCollections(List<CollectionsModel> collectionHelper) {
    for (int i = 0; i < 12; i++) {
        arrayListCollections.add(collectionHelper.get(i));
    }
    /*rest of code*/
}

RecyclerView 2的适配器方法:

private void setAdapterForRecyclerView(final List<CollectionsModel> wlls) {
    if (myAdapter == null) {
        myAdapter = new MyAdapterCollection(wlls, getActivity(), new RecyclerViewClickListener() {
            @Override
            public void onClick(View view, Wallpaper wallpaper) {

            }

            @Override
            public void onClick(View view, CollectionsModel collectionsModel) {

            }
        }, R.layout.collection_item);
        recyclerView.setAdapter(myAdapter);
    } else {
        int position = myAdapter.getItemCount();
        myAdapter.getItems().addAll(wlls);
        myAdapter.notifyItemRangeInserted(position, position);
    }
}

我的问题:

运行该应用程序时,我看到RecyclerView 1和RecyclerView 2都是随机的(顺序相同)。

我想要的东西:

我想查看随机项目的顺序为RecyclerView 1和正常顺序RecyclerView 2

1 个答案:

答案 0 :(得分:3)

首先,您要将列表对象传递给setAdapterForRecyclerView(collections);

之后,您将同一列表对象传递给setAdapterForRecyclerViewBestCollections(shuffleCollection(collections));

然后将对象改组(在使用相同对象和随机化的两种方法中,这将同时反映到RecyclerView1RecyclerView2

创建新的List对象,并在改组后返回该对象,这样您将在RecyclerView1RecyclerView2中看到两个不同的顺序

public List<CollectionsModel> shuffleCollection(List<CollectionsModel> collectionsModelList) {
    List<CollectionsModel> shuff = new ArrayList<>(collectionsModelList);
    java.util.Collections.shuffle(shuff);
    return shuff;
}