gpt4 book ai didi

Android Java,来自资源的位图

转载 作者:太空狗 更新时间:2023-10-29 16:08:40 25 4
gpt4 key购买 nike

我的图像在我的 res/drawable 文件夹中,这没有问题。问题是,我希望能够做这样的事情:

Bitmap mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.*img[contar]*);

换句话说,eclipse 不允许我这样做 img[contar] 它只接受图像文件的特定名称(例如:crystalblue),我想说 move从“crystalblue”到“crystalred”图像,在我的例子中,我需要一个变量来完成它。

观察:我确实将 img 声明为字符串数组。

有什么解决方案吗?

最佳答案

您不能将变量名的一半与运行时数据连接起来。编译器无法判断您实际尝试传递的变量是什么。

你要做的是这样的:

int resourceId = 0;
if(someCondition){
resourceId = R.drawable.someimage;
}else{
//other logic for picking the right image here
}

mBitmap = BitmapFactory.decodeResource(getResources(), resourceId);

您还可以使用反射在 R 类中查找名称与字符串数组中的值匹配的字段,然后对其执行“get”调用以填充 resourceId:

Class rClass = R.drawable.class;
Field resourceConstant =rClass.getField(img[contar]);
int resourceId = resourceConstant.getInt(null); //since it's a static field, pass null here
mBitmap = BitmapFactory.decodeResource(getResources(), resourceId);

关于Android Java,来自资源的位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8247015/

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