【问题标题】:How can I get an image resource by its name in Android? [duplicate]如何在 Android 中按名称获取图像资源? [复制]
【发布时间】:2016-07-06 19:25:56
【问题描述】:

我想创建一个国家和国旗选择器。我想设置一个标志的图像,但我想根据其名称选择该图像。基本上,我正在尝试为 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
}

【问题讨论】:

    标签: java android android-layout android-studio


    【解决方案1】:

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

    Resources | Android Developers

    示例

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

    【讨论】:

      猜你喜欢
      • 2014-05-08
      • 2021-11-22
      • 2011-03-03
      • 2013-04-28
      • 1970-01-01
      • 2015-01-30
      • 2011-09-30
      • 1970-01-01
      相关资源
      最近更新 更多