2016-07-06 128 views
1

我想创建一个国家和标志选择器。我想设置一个标志的图像,但我想根据它的名称选择该图像。 BAscially我正在尝试为android创建一个标志和ISD代码选择器,这样我就可以在电话号码用户之前使用它来添加ISD代码。如何通过Android中的名称获取图像资源?

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 
    } 

回答

3

您要找的缺件是Resources.getIdentifier()。您可以将名称作为字符串传入并获取整数标识符。

Resources | Android Developers

ex。

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