无法使用getResources()。getIdentifier获取资源

时间:2013-11-11 05:14:32

标签: android

我需要使用其名称来获取drawable,以便我可以在imageView.setImageDrawable()中设置它,它接受int值;

我正在使用的字符串是img_state_btn

代码:

int id = mContext.getResources().getIdentifier(icon, null,
                mContext.getPackageName());
imgView.setImageDrawable(mContext.getResources().getDrawable(id));

我收到了正确的套餐名称,但身份证的价值是0

我做错了什么?

P.S。 - 不想使用R.java

4 个答案:

答案 0 :(得分:2)

试试如下:

您可以通过以下代码获取图像的ID。

 int id= getResources().getIdentifier(imageName,"drawable", getPackageName());

答案 1 :(得分:1)

要从名称中获取可绘制ID,请使用以下代码。我认为问题是你传递的是null而不是" drawable"

int drawableResourceId = mContext.getResources().getIdentifier("nameOfDrawable", "drawable", mContext.getPackageName());

答案 2 :(得分:1)

int id = mContext.getResources().getIdentifier("drawable/"+drawablename, "drawable",mContext.getPackageName());

(或)

int id = mContext.getResources().getIdentifier(drawablename, "drawable",mContext.getPackageName());

这个

的JavaDoc
int android.content.res.Resources.getIdentifier(String name, String defType, String defPackage)



public int getIdentifier (String name, String defType, String defPackage) 
Added in API level 1
Return a resource identifier for the given resource name. A fully qualified resource name is of the form "package:type/entry". The first two components (package and type) are optional if defType and defPackage, respectively, are specified here. 

Note: use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.

Parameters
name  The name of the desired resource. 
defType  Optional default resource type to find, if "type/" is not included in the name. Can be null to require an explicit type. 
defPackage  Optional default package to find, if "package:" is not included in the name. Can be null to require an explicit package. 

Returns
int The associated resource identifier. Returns 0 if no such resource was found. (0 is not a valid resource ID.) 

答案 3 :(得分:-1)

您也可以直接设置

imgView.setImageResource(R.drawable.img_state_btn);