现在的位置: 首页 > 综合 > 正文

根据资源名来获得资源id

2013年08月29日 ⁄ 综合 ⁄ 共 652字 ⁄ 字号 评论关闭

在做开发的时需要一次性的加载同类型的图片,如果每次都去BitmapFactory.decodeResource(res, id) 有点繁琐

可以通过资源名来获得资源id

下面以加载52张扑克牌为例:

	/**
	 * 加载52张牌
	 */
	public void loadAllCard() {
		
		String[] type = { "clubs", "diamonds", "hearts", "spades" };
		String[] num = { "ace", "two", "three", "four", "five", "six", "seven",
				"eight", "nine", "ten", "jack", "queen", "king" };
		// 52张牌
		Bitmap[][] cardImages = new Bitmap[4][13];
		for (int i = 0; i < type.length; i++) {
			for (int j = 0; j < num.length; j++) {
				try {
					// 拼凑牌的名字
					String name = "card_" + num[j] + "_" + type[i] ;
					// 依据name取得Field对象
					Field f = R.drawable.class.getField(name);
					// 取得int值
					int resId = f.getInt(R.drawable.class) ;
					cardImages[i][j] = BitmapFactory.decodeResource(getResources(),resId);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

	}

抱歉!评论已关闭.