1

I want create a country and flag picker. I want to set an image of a flag, but I want to choose that image based on its name. Basically, I am trying to create a flag and ISD code picker for Android, so that I can use it for adding an ISD code before the phone number's user.

ImageView img1 = (ImageView)findViewById(R.id.imgFlag);
img1.setBackgroundResource(R.drawable.India_91);

Something like this in an adapter.

// India_91 is an image India_91.png,
// suppose if I have USA_1.png as image then i should be able to use
// string "USA_1" to get the related resource and set it as
// BackgroundResource.

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    long resId = getResourceIdUsingResourceString(arrayOfStrings[position]);
    // I should get the Id of the image
    // resource named as"USA_91"
}

// This is a utility function outside adapter class
long getResourceIdUsingResourceString(string resourceName) {
    // Here I want to add a code which can check for
    // resource name and then get id of it
    // which can then be used by callee function/block
    // to fetch the correct resource and display it
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Hemant Bavle
  • 3,297
  • 1
  • 24
  • 30

1 Answers1

4

The missing piece you are looking for is Resources.getIdentifier(). You can pass in the name as a String and get the integer identifier.

Resources | Android Developers

Example

long resId = parent.getResources().getIdentifier(arrayOfStrings[position], "drawable", mApplicationContext.getPackageName());
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
kris larson
  • 30,387
  • 5
  • 62
  • 74