【问题标题】:Retrieving a drawable resource by its name with function parameters通过函数参数的名称检索可绘制资源
【发布时间】:2026-01-08 07:40:01
【问题描述】:

我的可绘制文件夹中有四张图片:small_blue.jpg、small_green.jpg、big_blue.jpg 和 big_green.jpg

我创建了一个带有两个参数的函数:

public Bitmap getPic (String size, String color)
{
   return BitmapFactory.decodeResource( getResources(), R.drawable.small_blue);
} 

我需要用函数的参数改变R.drawable.small_blue中的small_blue 但我做不到:

R.drawable. + size + "_" + color

它是如何完成的?

非常感谢

【问题讨论】:

    标签: android function bitmap drawable


    【解决方案1】:

    试试这个:

    public Bitmap getPic (String size, String color)
    {
        return
            BitmapFactory.decodeResource
            (
                getResources(), getResourceID(size + "_" + color, "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;
        }
    }
    

    【讨论】: