如何通过android中的名字获取图像资源?

时间:2016-07-06 19:25:57

标签: java android android-layout android-studio

我想创建一个国家和国旗选择器。我想设置一个标志的图像,但我想根据它的名称选择该图像。 BAscially我正在尝试为Android创建一个标志和ISD代码选择器,以便我可以使用它在电话号码用户之前添加ISD代码。

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

适配器中有这样的东西。

//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 个答案:

答案 0 :(得分:3)

您正在寻找的缺失部分是Resources.getIdentifier()。您可以将名称作为String传递并获取整数标识符。

Resources | Android Developers

离。

long resId = parent.getResources().getIdentifier(arrayOfStrings[position], "drawable", mApplicationContext.getPackageName());