繁体   English   中英

随机排列ArrayList

[英]Shuffle ArrayList

我有两个RecyclerView和一个称为collections的 ArrayList ,我试图改组此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中看到随机物品的顺序

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

之后,您setAdapterForRecyclerViewBestCollections(shuffleCollection(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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM