如何在Android中按名称获取图片资源? [英] How to get an image resource by it's name in android?

查看:101
本文介绍了如何在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 it's name. BAscially I am trying to create a flag and ISD code picker for android so that I can use it for adding ISD code before the phone numbers 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.

资源|Android开发人员

例如.

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

这篇关于如何在Android中按名称获取图片资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆