How to get an image resource by it's name in android? [duplicate]

Deadly 提交于 2021-01-28 07:04:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!