gpt4 book ai didi

android - 使用函数参数按名称检索可绘制资源

转载 作者:行者123 更新时间:2023-11-30 03:06:57 25 4
gpt4 key购买 nike

我的 drawable 文件夹中有四张图片: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

这是怎么做到的?

非常感谢

最佳答案

试试这个:

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;
}
}

关于android - 使用函数参数按名称检索可绘制资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21646975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com