2016-07-06 162 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());