问题
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 it's name. BAscially I am trying to create a flag and ISD code picker for android so that I can use it for adding ISD code before the phone numbers 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
}
回答1:
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
ex.
long resId = parent.getResources().getIdentifier(arrayOfStrings[position], "drawable", mApplicationContext.getPackageName());
来源:https://stackoverflow.com/questions/38232209/how-to-get-an-image-resource-by-its-name-in-android