如何在recyclerview上随机播放图像

时间:2016-04-16 13:23:40

标签: android android-studio android-recyclerview shuffle

我想按下按钮点击我的网格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(数据);但它不工作,也许我不知道如何使用,我只是发现并尝试使用,我不知道,帮助我..

2 个答案:

答案 0 :(得分:3)

只需使用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);
    }
});

答案 1 :(得分:1)

在按钮的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());
    }
});