我使用以下代码通过手动给出每个名称从可绘制文件夹中获取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();
答案 0 :(得分:1)
我让它像这样工作。我相信有人可以做得更好......但这很有效。
警告:
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));
}
}
爱 Boober。
答案 1 :(得分:0)
您可以尝试使用循环获取可绘制的ID:
for(int=1; i<=9 ; i++)
{
getResources().getIdentifier("bird"+i,"drawable",getPackageName());
}