Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically set Source of the ImageView

I'm trying to set country flags in a ImageView according to country name.

I follows the convention that country flag image is always stored at drawable/flag_country_name

for eg; drawable/flag_india, drawable/flag_south_africa

Code I written so far is

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 works correctly.

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

like image 443
Mithun Sreedharan Avatar asked Feb 24 '23 14:02

Mithun Sreedharan


2 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 this one.

like image 186
Saurabh Pareek Avatar answered Mar 09 '23 06:03

Saurabh Pareek


U have to Store the country name and R.id Values....

When u want get those Values And display it

like image 40
kannappan Avatar answered Mar 09 '23 07:03

kannappan