如何在 Android 中按名称获取图像资源? [英] How can I get an image resource by its name in Android?
本文介绍了如何在 Android 中按名称获取图像资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个国家/地区和国旗选择器.我想设置标志的图像,但我想根据其名称选择该图像.基本上,我正在尝试为 Android 创建一个标志和 ISD 代码选择器,以便我可以使用它在电话号码的用户之前添加 ISD 代码.
I want create a country and flag picker. I want to set an image of a flag, but I want to choose that image based on its name. Basically, I am trying to create a flag and ISD code picker for Android, so that I can use it for adding an ISD code before the phone number's user.
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()
.您可以将名称作为字符串传入并获取整数标识符.
The missing piece you are looking for is Resources.getIdentifier()
. You can pass in the name as a String and get the integer identifier.
long resId = parent.getResources().getIdentifier(arrayOfStrings[position], "drawable", mApplicationContext.getPackageName());
这篇关于如何在 Android 中按名称获取图像资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文