Get Dynamic Drawable Name

Pratik 1803
Nov 2 · 1 min read

I had a scenario where I have to set team logo as per team id.

drawable directory
public int getTeamLogos(String teamId)
{
switch (teamId)
{
case "121":
return R.drawable.team_logo_121;
case "122":
return R.drawable.team_logo_122;
case "123":
return R.drawable.team_logo_123;
}
return 0;
}

Issue is everytime I add a new logo I have to update the function and add case to switch for it inorder to get the new logo.

public int getTeamLogos(String teamId)
{
switch (teamId)
{
case "121":
return R.drawable.team_logo_121;
case "122":
return R.drawable.team_logo_122;
case "123":
return R.drawable.team_logo_123;
case "124":
return R.drawable.team_logo_124;
}
return 0;
}

After searching …I found out a solution which will solve this problem.

  1. Create the drawable String uri with appending the teamId.
String uri = "@drawable/team_logo_"+teamId;

2. Get the image resource by passing this uri

int imageResource = getResources().getIdentifier(uri, null, getPackageName());

3. Get the drawable resource image

Drawable res = getResources().getDrawable(imageResource);

4. Now set the image.

ivImage.setImageDrawable(logoDrawable);

Overall the code will be like this

String uri = "@drawable/team_logo_"+teamId;int imageResource = getResources().getIdentifier(uri, null, getPackageName());Drawable logoDrawable = getResources().getDrawable(imageResource);ivImage.setImageDrawable(logoDrawable)

Happy coding :) { Keep improving the things in braces }

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade