简体   繁体   中英

numbered images on setImageResource

I'm working on an Android App, and I had the following code:

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.

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...

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. not a image name. so when you are adding a digit to the resource id it is setting the image of next id. as your images' names are sequential so the ids were also sequential that's why you got successful result. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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