图像在回收站视图中重复出现

时间:2016-08-04 10:42:18

标签: android image random android-recyclerview

我有一组图像以随机方式显示在Recycler View中。问题是图像重复而不是所有图像都被使用。我需要的是:所有使用的图像,每次只显示一次(不重复)。提前感谢您的帮助。

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)); //试图使用它但没有成功

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

}

编辑:我的适配器代码

公共类MyAdapter扩展了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();

}

2 个答案:

答案 0 :(得分:1)

将您的文章类更改为:

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;
    }
}

然后当您创建适配器时,将Article.getRandomArticles()作为文章列表传递,如下所示:

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

编辑:忘记了getRandomArticles的返回类型

答案 1 :(得分:0)

您已经在洗牌并再次从该洗牌阵列中挑选随机图像。随机选择会让您再次获得相同的图像。因此,只需按照随机顺序从阵列中选择图像。无需挑选随机图像。

修改

将您的数组更改为列表并尝试以下内容:

public static ArrayList<Integer> sTitles = new ArrayList<Integer>();
sTitles.add(R.drawable.image1a);
.
.
.
.
sTitles.add(R.drawable.image30a);
Collections.shuffle(sTitles );