Pawel Pawel - 4 months ago 38
Android Question

Images repeat in recycler view

I have set of images to display in Recycler View in random way. The issue is that images repeat and not all images are used. What I need is: all images used and display each of them only once (no repeat). Thank you in advance for help.

public class Article {
private int mTitle;

private static int[] sTitles = {
R.drawable.image1a,
R.drawable.image2a,
....
R.drawable.image30a
};
public Article() {

Random random = new Random();


// Collections.shuffle(Arrays.asList(sTitles));// Tried to use this but no success

mTitle = sTitles[random.nextInt(sTitles.length)];
}
public int getTitle() {
return mTitle;

}


Edit: My adapter code

public class MyAdapter extends RecyclerView.Adapter {

private ArrayList<Article> mArticles = new ArrayList<>();


public RecyclerView mRecyclerView;

private class MyViewHolder extends RecyclerView.ViewHolder {

public ImageView mTitle;


public MyViewHolder(View pItem) {
super(pItem);

mTitle = (ImageView) pItem.findViewById(R.id.imageView);
}
}

public MyAdapter(ArrayList<Article> pArticles, RecyclerView pRecyclerView) {
mArticles = pArticles;
mRecyclerView = pRecyclerView;


}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, final int i) {

View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.article_layout, viewGroup, false);

return new MyViewHolder(view);
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, final int i) {

Article article = mArticles.get(i);

((MyViewHolder) viewHolder).mTitle.setImageResource(article.getTitle());

}

@Override
public int getItemCount() {
return mArticles.size();

}

Answer

Change your Article class to this:

public class Article {
    private int mTitle;

    private static int[] sTitles = {
            R.drawable.image1a,
            R.drawable.image2a,
            ....
            R.drawable.image30a
    };

    public Article(int title) {
        this.mTitle = title;
    }

    public int getTitle() {
        return mTitle;
    }

    public static ArrayList<Integer> getRandomArticles() {
        ArrayList<Integer> titles = new ArrayList<>();
        ArrayList<Integer> tempTitles = new ArrayList<Integer>(Arrays.asList(sTitles));
        Collections.shuffle(tempTitles);
        for(int title : tempTitles) {
            titles.add(title);
        }
        return titles;
    }
}

Then when you create your Adapter pass Article.getRandomArticles() as the Article List like this:

new MyAdapter(Article.getRandomArticles(), yourRecyclerView);

EDIT: Forgot the return type of getRandomArticles

Comments