Get Dynamic Drawable Name
Nov 2 · 1 min read
I had a scenario where I have to set team logo as per team id.

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