11

I have many icon in drawable folder and I have their name as String. How can I access to drawable folder and change background imageView (or any view) use these name in dynamically. Thanks

4

6 回答 6

34

这可以使用反射来完成:

String name = "your_drawable";
final Field field = R.drawable.getField(name);
int id = field.getInt(null);
Drawable drawable = getResources().getDrawable(id);

或使用Resources.getIdentifier()

String name = "your_drawable";
int id = getResources().getIdentifier(name, "drawable", getPackageName());
Drawable drawable = getResources().getDrawable(id);

然后在任何一种情况下使用它来设置drawable:

view.setBackground(drawable)
于 2014-02-18T14:13:30.017 回答
7
int resId = getResources().getIdentifier("your_drawable_name","drawable",YourActivity.this.getPackageName());
Drawable d = YourActivity.this.getResources().getDrawable(resId);
于 2014-02-18T14:12:07.570 回答
5

可以这样做:

ImageView imageView = new ImageView(this);
imageView.setBackground(getResources().getDrawable(getResources().getIdentifier("name","id",getPackageName())));
于 2014-02-18T14:11:03.627 回答
3

尝试这个:

public Bitmap getPic (int number)
{
    return
        BitmapFactory.decodeResource
        (
            getResources(), getResourceID("myImage_" + number, "drawable", getApplicationContext())
        );
}

protected final static int getResourceID
(final String resName, final String resType, final Context ctx)
{
    final int ResourceID =
        ctx.getResources().getIdentifier(resName, resType,
            ctx.getApplicationInfo().packageName);
    if (ResourceID == 0)
    {
        throw new IllegalArgumentException
        (
            "No resource string found with name " + resName
        );
    }
    else
    {
        return ResourceID;
    }
}
于 2014-02-18T14:11:48.410 回答
1

如果您将文件名作为字符串,您可以使用:

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

使用此 ID,您可以像往常一样访问它(假设它是可绘制的):

Drawable drawable = getResources().getDrawable(id);
于 2014-02-18T14:09:50.620 回答
0

如果不在任何活动中,则使用@FD_ 示例

笔记:

如果您没有进行任何活动,则必须发送上下文参数才能使用“getResources()”或“getPackageName()”,并且不推荐使用“getDrawable(id)”,请改用 getDrawer(int id, Theme theme)。(主题可以为空):

String name = "your_drawable";
int id = context.getResources().getIdentifier(name, "drawable", 
context.getPackageName());
Drawable drawable = context.getResources().getDrawable(id, null);
于 2016-07-14T18:23:58.757 回答