简体   繁体   中英

Getting resource from name instead of id in android

I have the following code for getting a resource using name instead of id:

spec = new ImageView[56];
for (i=2; i<=56; i++) {
    String s = null;
    s = "items_r"+Integer.toString(i)+"_c1";
    spec[i] = (ImageView) findViewById(getResources().getIdentifier(s,"drawable",getPackageName()));
    Log.e(tag, Boolean.toString(spec[i] == null));
}

I have 56 items in my drawable folder named items_r1_c1 to items_r56_c1;
But I am getting spec[i] as null.
Could someone point me towards my error and how to correct it?
Thank you.

findViewById(int) is for finding View s that have already been inflated and that currently exist under your Activity's content view.

You'll want to use Resources.getDrawable(int) or ImageView.setImageResource(int) .

spec = new ImageView[56];
for (i=2; i<=56; i++) {
    String res = "items_r" + Integer.toString(i) + "_c1";
    int resId = getResources().getIdentifier(res, "drawable", getPackageName());
    spec[i] = new ImageView();
    // Drawable image = getResources.getDrawable(resId);
    // spec[i].setImageDrawable(image);
    spec[i].setImageResource(resId);
    Log.e(tag, Boolean.toString(spec[i] == null));
}

Try this

int id = findViewById(getResources().getIdentifier(s,"drawable",getPackageName());
spec[i] = (new ImageView()).setImageResource(id);

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