Changing Imageview on button dynamically

2020-07-16 03:14发布

In my application, I have button and ImageView.

Here when i press button i want to change ImageView. I have 5 images in my drawable folder. On press button ImageView changes images one by one based on button click. I want it's solution.

Grateful to anyone that can help.

2条回答
够拽才男人
2楼-- · 2020-07-16 03:30

As @Nizam said just maintain an array of id and load dinamically the image in the onClick(). Instead of the Random use a field variable and increment it. Be careful to the array length!

final int[] ids = new int[] { R.drawable.img1, R.drawable.img2 };
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        int randomId = new Random().nextInt(ids.length);
        ImageView imageView = (ImageView) findViewById(R.id.imageview);
        imageView.setImageDrawable(getResources().getDrawable(randomId));
    }
});
查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-07-16 03:46

Maintain an array of image ids and inside onClick, set images using id from the array, then increment index.

Eg:-

ArrayList<Integer> ids=new ArrayList<Integer>();
        ids.add(R.drawable.image1);
        ids.add(R.drawable.image2);
        ids.add(R.drawable.image3);
        ids.add(R.drawable.image4);
        ids.add(R.drawable.image5);
Int index=0
        b.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
if(index<ids.size()){
      imageview.setImageResource(ids.get(index));
       index++;
   }
 else index=0;
 }
 });
查看更多
登录 后发表回答