java - 如何在 Android 中通过名称获取图像资源?

标签 java android android-layout android-studio

<分区>

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

最佳答案

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

Resources | Android Developers

例子

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

关于java - 如何在 Android 中通过名称获取图像资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38232209/

相关文章:

java - 在 jasper 报告中设置报告区域的大小

java - 如何打包包含哈希​​映射的类对象? Kotlin

android - 为什么 Xamarin.Forms WebView 会增加 Android 应用程序存储数据大小?

Android:居中图像

Android:从全屏返回后,内容高度偏移了一些像素

java - Android hashmap 返回 null

java - Hibernate - 未能延迟初始化角色集合 : could not initialize proxy - no Session

java - Java中允许有一处不匹配的KMP算法

java - Android Material 按钮切换组

android - 将 jetpack compose 添加到现有项目