如何在arraylist中制作图像不重复

时间:2018-03-13 03:49:31

标签: android

如何让这些图像不重复?我尝试使用hashset但它没有用,请帮助我。我只需要显示1张图片,并且每次点击按钮时都不会重复,当显示所有图片时,应用程序将结束帮助我们。在此先感谢您给出答案。这是我的代码

ImageView imgname, imgname1;

ArrayList<Integer> animals;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    imgname = (ImageView) findViewById(R.id.imgname);
    imgname1 = (ImageView) findViewById(R.id.imgname1);


    imgname1.setVisibility(View.INVISIBLE);


    animals = new ArrayList<>();


    animals.add(109);//fish
    animals.add(110);//fish
    animals.add(112);//fish
    animals.add(113);//fish
    animals.add(114);//fish
    animals.add(111);//fish
    animals.add(209);//arachnid




    imgname.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view){
            //shuffle the images
            Collections.shuffle(animals);

                assignImages(animals.get(0), imgname1);
                imgname1.setVisibility(View.VISIBLE);

        }
    });
}


public void assignImages(int animals, ImageView image){
    switch (animals){
        case 109:
            image.setImageResource(R.drawable.ears);
            break;
        case 110:
            image.setImageResource(R.drawable.eyes);
            break;
        case 112:
            image.setImageResource(R.drawable.hand);
            break;
        case 113:
            image.setImageResource(R.drawable.hearing);
            break;

    }

}

2 个答案:

答案 0 :(得分:0)

只需删除已显示的images并将其复制到新的temp数组,以保持原始数组不变

ArrayList<Integer> temp = new ArrayList<>();
temp.addAll(animals);
imgname.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view){
            //shuffle the images
           if(temp.size() > 0){
                Collections.shuffle(temp);
                int imageTobeShown = temp.get(0); 
                assignImages(imageTobeShown , imgname1);
                temp.remove(imageTobeShown);
                imgname1.setVisibility(View.VISIBLE);
           }else{
              //ended showing all images   
           }
      }
    });

答案 1 :(得分:0)

我这样做了......

final ArrayList temp = new ArrayList&lt;&gt;();         temp.addAll(动物);

    imgname.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view){
            if(temp.size() > 0){
                Collections.shuffle(temp);
                assignImages(temp.get(0) , imgname1);
                temp.remove(temp.get(0));
                imgname1.setVisibility(View.VISIBLE);
            }else{
                Toast.makeText(MainActivity.this, "Please press back again to exit!", Toast.LENGTH_SHORT).show();
            }

        }
    });
}