简体   繁体   English

通过java在android中的imageView上更改图像

[英]Changing image on imageView in android via java

I have a imageView, button inside an activity, 10 pictures that are named from stage1 to stage9. 我有一个imageView,一个活动内的按钮,从stage1到stage9命名的10张图片。

I need you help to solve some problem 我需要你帮忙解决一些问题

I would like to use a button click to change picture that is on imageView to the next one. 我想使用按钮单击将imageView上的图片更改为下一张。

I mean, I want to press on the button, and image view shows stage2 image, I press the button again and stage3 picture will be shown. 我的意思是,我想按按钮,图像视图显示stage2图像,再次按按钮,将显示stage3图片。

I have done this using counter var which count number of clicks and then running if statment to see which picture should go next, but it is too long and it is not possible to have more or less pictures. 我使用计数器var来完成此操作,该计数器对点击次数进行计数,然后运行语句以查看接下来应显示的图片,但是它太长了,不可能有更多或更少的图片。

I would like to know is there a way to do this, and if possible please show me how. 我想知道有没有办法做到这一点,请告诉我如何做。

Thanks 谢谢

code

private void changeImage(int counter) {
    if (counter == 1) {
        image.setImageResource(R.drawable.stage2);
    } else if (counter == 2) {
        image.setImageResource(R.drawable.stage3);
    } else if (counter == 3) {
        image.setImageResource(R.drawable.stage4);
    } else if (counter == 4) {
        image.setImageResource(R.drawable.stage5);
    } else if (counter == 5) {
        image.setImageResource(R.drawable.stage6);
    } else if (counter == 6) {
        image.setImageResource(R.drawable.stage7);
    } else if (counter == 7) {
        image.setImageResource(R.drawable.stage8);
    } else if (counter == 8) {
        image.setImageResource(R.drawable.stage9);
    }       
}

bassically this is the code that I am using right now. 糟糕的是,这是我现在正在使用的代码。

It works, but if I want to do it to be more dynamic. 它有效,但是如果我想使其更具动态性。

Just get resource id by name, use like, 只需按名称获取资源ID,就可以这样使用,

private void changeImage(int counter) {

     if(counter >= 1 && counter <= 9) // Always check counter value before accessing as resource id
     {
      int counterValue = counter+1;  
      int resourceId = Resources.getSystem().getIdentifier("stage"+counterValue, "drawable",  this.getPackageName()); // Use application context to get package name
      image.setImageResource(resourceId);
     }
} 

You'll need to tell the vm to update -> 'invalide()'. 您需要告诉虚拟机进行更新->'invalide()'。

Or use Picasso, 或使用毕加索

Picasso.with(Statics.context).load(R.drawable.stageX).error(R.drawable.error_img).resize(width, height).priority(Priority.HIGH).into(image);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM