如何在活动开始时随机显示图像

时间:2015-04-03 08:24:50

标签: android eclipse

我想在活动开始时随机显示图片。我使用以下代码来执行它。

final ImageView img = (ImageView) findViewById(R.id.imgRandom);

        final String str = "img_" + rnd.nextInt(2);
        img.setImageDrawable(getResources().getDrawable(
                getResourceID(str, "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;
        }

    }

问题:此代码仅随机生成我的drawable中出现的前两个图像,而我总共有8个图像。

提前致谢。

P.S我的图片名称是img_0,img_1,img_2,img_3,img_4,img_5,img_6,img_7

1 个答案:

答案 0 :(得分:0)

  1. 使用HashMap存储与密钥相关联的图像名称

    HashMap<Integer, String> meMap=new HashMap<Integer, String>();
    meMap.put(0,"img_0"); // add other images as 1, 2, 3
    
  2. 使用Random类生成包含0且小于8的数字

    Random rnd = new Random();
    int value = rnd.nextInt(8);
    
  3. 根据生成的密钥(随机整数)获取相关的地图对象,并获取相应的图像名称并加载它。