Dynamically set the image source Image

I am trying to set country flags in ImageView according to country name.

I agree that the country flag image is always stored in drawable/flag_country_name

eg; drawable / flag_india, drawable / flag_south_africa

The code I wrote so far,

 imageFlagRight.setImageResource(getFlagResource("India")); private int getFlagResource(String teamName) { if(teamName.equals("India")){ return R.drawable.flag_india; } if(teamName.equals("Srilanka")){ return R.drawable.flag_srilanka; } if(teamName.equals("New Zealand")){ return R.drawable.flag_new_zealand; } if(teamName.equals("Pakistan")){ return R.drawable.flag_pakistan; } if(teamName.equals("Srilanka")){ return R.drawable.flag_srilanka; } if(teamName.equals("South Africa")){ return R.drawable.flag_south_africa; } if(teamName.equals("Austalia")){ return R.drawable.flag_australia; } return R.drawable.flag_default; } 

The above code is working correctly.

Now I want to add more counties and flags. Is there a way to reduce code lines? like return R.drawable.flag+underscorise(teamName);

+4
source share
4 answers
 String name="flag_" + "india"; public int getFlagResource(Context context, String name) { int resId = context.getResources().getIdentifier(name, "drawable", "com.mypackage.namehere"); return resId; } 

Try it.

+6
source

U need to save the name of the country and the value of R.id ....

When you want to get these values ​​and display it

+1
source

When entering from @Saurabh Pareek

 private int getFlagResource(String teamName) { String flagString = "flag_"+teamName.replace(" ", "_").toLowerCase(); int resId = getContext().getResources().getIdentifier(flagString, "drawable", "com.mypackage.namehere"); if(resId != 0){ return resId; } return R.drawable.flag_default; } 
+1
source
 <yourimageview>.setImageViewResource(getFlagResource("india")); 
0
source

Source: https://habr.com/ru/post/1347034/


All Articles