简体   繁体   English

setImageResource上编号的图像

[英]numbered images on setImageResource

I'm working on an Android App, and I had the following code: 我正在使用Android应用程序,并且有以下代码:

int digit = 0;
imageButton = (ImageView)findViewById(R.id.btn1);
numberedImage = (ImageView)findViewById(R.id.Digit1);

imageButton.setOnClickListener(new OnClickListener()
{
    public void onClick(View v)
        {
             digit++;
             numberedImage.setImageResource(R.drawable.number + ((digit) + 1));
        }
});

and some images on a drawable folder called number1 , number2 , and so on... This code was working perfectly, and then, suddenly, it's not working anymore. 以及一些名为number1number2等等的可绘制文件夹中的图像,等等……此代码运行正常,然后突然不起作用了。

I want the ImageView to change the images each click, and what made me completely confused, is the fact that this code was working completely fine (even though it might be wrong some way, I'm not a programmer), and all of the sudden, it's not anymore... 我希望ImageView每次单击都更改图像,这让我感到完全困惑,是因为该代码运行得很好(即使某种方式可能是错误的,我不是程序员),并且所有这些突然之间,不再...

After that I also tried using arrays and loops, but I encountered the same error: 之后,我也尝试使用数组和循环,但是遇到了相同的错误:

"number cannot be resolved or is not a field" “数字无法解析或不是字段”

which wasn't a problem before. 这以前不是问题。

You have some misunderstanding. 你有些误会。 But may be fortunately(or unfortunately) your code gave you some successful result for which your misunderstanding was more firmed. 但是幸运的是(或不幸的是)您的代码给您带来了一些成功的结果,而您的误解更加坚定了。

ImageView.setImageResource takes a resource id as parameter. ImageView.setImageResource将资源ID作为参数。 not a image name. 不是图片名称。 so when you are adding a digit to the resource id it is setting the image of next id. 因此,当您向资源ID添加数字时,它会设置下一个ID的图像。 as your images' names are sequential so the ids were also sequential that's why you got successful result. 由于您的图片名称是连续的,因此ID也是连续的,这就是您获得成功结果的原因。 But it is not guranteed that you will always be getting that done. 但这并不保证您将始终做到这一点。

I guess previously it was working because there was an image named number in your resource. 我猜以前是可行的,因为您的资源中有一个名为数字的图像。 But now it is removed. 但是现在将其删除。

Proposed solution 拟议的解决方案

Resources res = getResources();
String mDrawableName = "number" + digit + 1; // be sure those exist
int resID = res.getIdentifier(mDrawableName , "drawable", getPackageName()); numberedImage.setImageResource(resId);

please kindly use 请使用

for(int i=0;i<imageCount;i++){
    int imageResId = getResources().getIdentifier("image" + i, "id", YourActivity.this.getPackageName());
    numberedImage.setImageResource(imageResId);
}

in order to access image by resource name. 为了通过资源名称访问图像。

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

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