繁体   English   中英

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

[英]Changing image on imageView in android via java

我有一个imageView,一个活动内的按钮,从stage1到stage9命名的10张图片。

我需要你帮忙解决一些问题

我想使用按钮单击将imageView上的图片更改为下一张。

我的意思是,我想按按钮,图像视图显示stage2图像,再次按按钮,将显示stage3图片。

我使用计数器var来完成此操作,该计数器对点击次数进行计数,然后运行语句以查看接下来应显示的图片,但是它太长了,不可能有更多或更少的图片。

我想知道有没有办法做到这一点,请告诉我如何做。

谢谢

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

糟糕的是,这是我现在正在使用的代码。

它有效,但是如果我想使其更具动态性。

只需按名称获取资源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);
     }
} 

您需要告诉虚拟机进行更新->'invalide()'。

或使用毕加索

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