简体   繁体   中英

set image with setImageResource in Android Studio using a variable

I am trying to set my image in my ImageView through a variable (item is the variable name, which I will be setting to lowerCase). However, it is not working and resID will return 0.

Here is my code:

    ImageView iv = (ImageView)v.findViewById(R.id.imgView);

    if (item != null) {
        Log.i("item: ", item.toLowerCase());

        int resID = getResources().getIdentifier(item.toLowerCase(), "drawable", "package.name");

        Log.i("resid: ", String.valueOf(resID)); //will return 0 - im guessing this is where the problem is

        iv.setImageResource(resID);
    }

I used this as a guide Android, reference things in R.drawable. using variables? but none of the other solutions work for me, in fact they all gave me the same result (returning 0). I can provide more code if needed (just didn't want it to be bombastic). Thanks in advance!

getIdentifier() Returns 0 if no such resource was found. (0 is not a valid resource ID.)

and you should getPackageName() method of the context object which always return the correct package name.

if you will show your folder stracture and file's names i can help you to fix it.

btw, if you can get the drawable directly from the resource you can just use R.drawable.resName

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