Code Lover
Code Lover

Reputation: 8378

Getting a drawable using for loop index

I am designing UI and for that need to populate some dummy content for recyclerview. So I thought to create using for loop so it makes life easier if I want to change the number.

I have drawable resources (images) that suffix with numbers. for instance

avatar_1, avatar_2, avatar_3, ...
featured_1, featured_2, featured_3, ...

I have tried setting R.drwable.featured_ + i and as expected it didn't work and end up with an error.

This is what I am using

...

for (int i = 0; i <= 11; i++) {

    int username = random.nextInt(userNames.length);
    int catInt   = random.nextInt(categories.length);
    int time     = random.nextInt(times.length);

    mBlogs.add(new Blog(
            R.drawable.featured_ + i, // this
            R.drawable.avatar_ + i, // this
            getString(R.string.blog_title),
            categories[catInt],
            getString(R.string.blog_excerpt),
            userNames[username],
            times[time],
            random.nextBoolean(),
            random.nextBoolean()
    ));
}

...

Question: How can I get resource within the loop by loop index?

Upvotes: 1

Views: 141

Answers (2)

shb
shb

Reputation: 6277

You can use getIdentifier

for (int i = 0; i <= 11; i++) {
    int featuredResId = getResources().getIdentifier("featured_" + i, "drawable", getPackageName())
    int avatarResId = getResources().getIdentifier("avatar_" + i, "drawable", getPackageName())
    //...
    mBlogs.add(new Blog(
            featuredResId,
            avatarResId,
            //...
    ));
}

Upvotes: 1

Ethan Choi
Ethan Choi

Reputation: 2409

Try as below.

//find drawable resource id 
public int getDrawableId(Context context, String name) 
{
    try {
        return getResources().getIdentifier(name, "drawable", context.getPackageName());
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    } 
}
...
for (int i = 0; i <= 11; i++) {
    int username = random.nextInt(userNames.length);
    int catInt   = random.nextInt(categories.length);
    int time     = random.nextInt(times.length);
    int featuredRes = getDrawableId(context, "featured_" + i);
    int avatarRes = getDrawableId(context, "avatar_" + i);

    // if not found any resource
    if (featuredRes == 0) featuredRes = R.drawable.featured_default

    if (avatarRes == 0) avatarRes = R.drawable.avatar_default

    mBlogs.add(new Blog(
            featuredRes,
            avatarRes,
            getString(R.string.blog_title),
            categories[catInt],
            getString(R.string.blog_excerpt),
            userNames[username],
            times[time],
            random.nextBoolean(),
            random.nextBoolean()
    ));
}
...

Upvotes: 2

Related Questions