1

我需要使用其名称获取可绘制对象,以便可以将其设置imageView.setImageDrawable()为 int 值;

我使用的字符串是,img_state_btn.

代码:

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

我收到正确的包名称,但 id 的值是0.

我在哪里做错了?

PS - 不想使用 R.java

4

4 回答 4

2

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

int drawableResourceId = mContext.getResources().getIdentifier("nameOfDrawable", "drawable", mContext.getPackageName());
于 2013-11-11T05:19:26.850 回答
2

尝试如下:

您可以通过以下代码获取带有名称的图像的 ID。

 int id= getResources().getIdentifier(imageName,"drawable", getPackageName());
于 2013-11-11T05:16:42.693 回答
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.) 
于 2013-11-11T05:22:09.703 回答
-1

也可以直接设置

imgView.setImageResource(R.drawable.img_state_btn);
于 2013-11-11T05:16:57.933 回答