如何在recyclerview上随机播放图像

how to shuffle image on recyclerview

我想在单击按钮时打乱我的网格 recylerview。我该怎么做

这是我的代码。

public class MainActivity extends AppCompatActivity {

Toolbar toolbar;
Context mContext;
Button suffle;
List<ImageData> data = new ArrayList<>();
 Recycle_Adapter adapter = new Recycle_Adapter(mContext, data);
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    toolbar = (Toolbar)findViewById(R.id.app_bar);
    setSupportActionBar(toolbar);
    assert getSupportActionBar() != null;
    getSupportActionBar().setHomeButtonEnabled(true);
    suffle = (Button)findViewById(R.id.suffle);

    for(int i =0;i<Glob.imgs.length;i++) {
        data.add(new ImageData(Glob.imgs[i]));
    }

    try {
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycleGridView);
        //recyclerView.setLayoutManager(new LinearLayoutManager(this));
         recyclerView.setLayoutManager(new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL));
         recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);


    }catch (NullPointerException e){
        e.printStackTrace();
    }

    suffle.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });

}

我用了Collections.Shuffle(数据);但它不起作用,也许我不知道如何使用,我只是找到并尝试使用,我不知道,帮助我..

在按钮的 onClick 中进行随机播放。 然后像这样调用 adapter.notifyItemRangeChanged():

suffle.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // Create this method in your adapter class and inside it call
        // shuffle on the list of items
        adapter.shuffleList(); 
        // Then notify the adapter that changes have been made to the list
        adapter.notifyItemRangeChanged(0, adapter.getItemCount());
    }
});

只需使用 Collections.shuffle(list) 打乱您的列表并将打乱后的列表提供回适配器,如下所示

suffle.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        Collections.shuffle(data);

        adapter = new Recycle_Adapter(mContext, data);
        recyclerView.swapAdapter(data, false);
    }
});