gpt4 book ai didi

android - 如何使用 Drawable 从 drawable 文件夹中获取所有图像作为位图数组?

转载 作者:行者123 更新时间:2023-11-29 01:02:59 31 4
gpt4 key购买 nike

我使用下面的代码通过手动给每个名称从 drawable 文件夹中获取 9(bird1 到 bird9)图像。

我如何使用数组或将 R.drawable.bird1 替换为变量(因为下面的语句只接受实际值)来获取数组中的所有 9 个图像?

Drawable myDrawable = ResourcesCompat.getDrawable(getApplicationContext().getResources(), R.drawable.bird1, null);
bitmap1 = ((BitmapDrawable) myDrawable).getBitmap();
myDrawable = ResourcesCompat.getDrawable(getApplicationContext().getResources(), R.drawable.bird2, null);
bitmap2 = ((BitmapDrawable) myDrawable).getBitmap();

最佳答案

我是这样操作的。我敢肯定有人可以做得更好……但这行得通。

注意事项:

1) 请记住将“com.example”替换为您的真实包名。

2) 将“numberOfBirdsBitmaps = 3”替换为您拥有的数量。

3) “derp”ImageViews 仅用于我的测试目的。

public class MainActivity extends AppCompatActivity {

int numberOfBirdsBitmaps = 3;

ArrayList<Bitmap> birdBitmapArray = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ImageView derp1 = (ImageView) findViewById(R.id.imageView);
ImageView derp2 = (ImageView) findViewById(R.id.imageView2);
ImageView derp3 = (ImageView) findViewById(R.id.imageView3);

for (int i = 0; i<numberOfBirdsBitmaps; i++) {

String temporaryString = "bird" + ((Integer) (i+1)).toString();

int temporaryIdentifier = getResources().getIdentifier(temporaryString, "drawable","com.example");

Drawable temporaryDrawable = ResourcesCompat.getDrawable(getApplicationContext().getResources(), temporaryIdentifier, null);

Bitmap temporaryBitmap = ((BitmapDrawable) temporaryDrawable).getBitmap();

birdBitmapArray.add(temporaryBitmap);

}

derp1.setImageBitmap(birdBitmapArray.get(0));

derp2.setImageBitmap(birdBitmapArray.get(1));

derp3.setImageBitmap(birdBitmapArray.get(2));


}
}

爱,布伯。

关于android - 如何使用 Drawable 从 drawable 文件夹中获取所有图像作为位图数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49690931/

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