【问题标题】:How to load multiple drawables from id using a loop?如何使用循环从 id 加载多个可绘制对象?
【发布时间】:2012-06-22 08:52:46
【问题描述】:

必须是循环通过此代码的方式:

private void loadSprites() {
    this.sprites[0] = BitmapFactory.decodeResource(getResources(), R.drawable.ic_boom01);
    this.sprites[1] = BitmapFactory.decodeResource(getResources(), R.drawable.ic_boom02);
    this.sprites[2] = BitmapFactory.decodeResource(getResources(), R.drawable.ic_boom03);
    this.sprites[3] = BitmapFactory.decodeResource(getResources(), R.drawable.ic_boom04);
    this.sprites[4] = BitmapFactory.decodeResource(getResources(), R.drawable.ic_boom05);
    this.sprites[5] = BitmapFactory.decodeResource(getResources(), R.drawable.ic_boom06);
    this.sprites[6] = BitmapFactory.decodeResource(getResources(), R.drawable.ic_boom07);
}

谢谢!

【问题讨论】:

  • 你想在哪里显示这些图像??在列表视图或 GridView 中?什么?
  • 你可以像我对这个问题的回答一样使用反射stackoverflow.com/questions/7441419/…
  • @KrishnaSuthar 它真的不重要。

标签: android resources


【解决方案1】:

如果我理解你的问题,你想要类似的东西,

int[] drawables = {R.drawable.ic_boom01,R.drawable.ic_boom02,R.drawable.ic_boom03,R.drawable.ic_boom04,R.drawable.ic_boom05,R.drawable.ic_boom06,R.drawable.ic_boom07}


private void loadSprites() {
for(int i=0; i<this.sprites.length; i++)
    this.sprites[i] = BitmapFactory.decodeResource(getResources(), drawables[i]);
}

【讨论】:

  • 是的,但我也不想硬编码 R.drawable.ic_boom ID。非常感谢。
  • 再次感谢,我一直在寻找像 AssetManager 这样的优雅解决方案。非常感谢您的回答。
【解决方案2】:

您应该将图像放在资产文件夹中。从他们那里,您可以通过他们的文件名访问它们。见http://developer.android.com/reference/android/content/res/AssetManager.html

【讨论】:

  • 好! AssetManager 是我需要的。谢谢!
【解决方案3】:

请看下面的代码。

先制作int数组

int[] mImgArray = { R.drawable.ic_boom01, R.drawable.ic_boom02,
            R.drawable.ic_boom03, R.drawable.ic_boom04, R.drawable.ic_boom05,
            R.drawable.ic_boom06, R.drawable.ic_boom07 };

或使用以下代码将此图像设置为 ImageView

mImgView1.setImageResource(mImgArray[0]);

您可以使用以下代码将此图像直接转换为位图并存储到位图数组中。

Bitmap mBmpArray=new Bitmap[mImgArray.length];
for(int i=0; i<mImgArray.length; i++)
    mBmpArray[i] = BitmapFactory.decodeResource(getResources(), mImgArray[i]);
}

【讨论】:

  • 谢谢,但是,这就是我试图避免在数组中硬编码大量 ID 的原因。
【解决方案4】:

这对我有用

//Bitmap of images for fly asset
     private Bitmap fly[] = new Bitmap[8];
    
    //Initialize array of images
    for(int i = 0; i < fly.length; i++){
                this.fly[i] = BitmapFactory.decodeResource( getResources(), getResources().getIdentifier("fly_frame" + i, "drawable", context.getPackageName() ) );
    }

【讨论】:

    【解决方案5】:

    您可以在一个简单的 for 循环中执行此操作.. 从第一个 id 开始并在每个循环中将其递增 1.. 虽然我不建议您这样做..

    【讨论】:

      猜你喜欢
      • 2011-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多