【问题标题】:Android Random resourcesAndroid 随机资源
【发布时间】:2011-03-20 00:12:05
【问题描述】:
String rank[] = {"tclub1.png", "tclub2.png", "tclub3.png", "tclub4.png",
  "tclub5.png", "tclub6.png", "tclub7.png", "tclub8.png", "tclub9.png",
  "tclub10.png", "tclub11.png", "tclub12.png", "tclub13.png"};

Random randInt = new Random();
int b = randInt.nextInt(rank.length);
String d = ("tclub" + b + ".png");
Log.v(LOG_TAG, "in value:=" + d);

上面是代码。 实际上,我的数组给了我一个介于(0 到 12)之间的随机索引。之后,我将其附加为图像名称。例如(tclub1.png) 现在它给我的图像名称是字符串格式。 我现在如何随机分配此图像?

【问题讨论】:

标签: android random


【解决方案1】:

如果要将图像加载到 ImageView,可以这样做:

String imgName = "tclub1"; // the image you want to load
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());  
imageView.setImageResource(id); 

【讨论】:

  • 嗨 itik.. 谢谢.. 但它没有发生。当我使用日志标签查看 ID 的值时,它显示为 0,而不是随机设置图像
  • 所有图像都位于 res/drawable 中吗?此外,图像名称应不含“.png”。 (它应该只是资源名称)
  • 非常感谢您的建议。上帝保佑你
【解决方案2】:

找到控件:

ImageView image = (ImageView) findViewById(R.id.rockId);

要从 drawable 动态加载图像,我使用这个辅助函数

public static int getDrawable(Context context, String name)
{
    Assert.assertNotNull(context);
    Assert.assertNotNull(name);

    return context.getResources().getIdentifier(name,
            "drawable", context.getPackageName());
}

这将返回您的可绘制对象的 id,现在您只需在控件中设置图像:

image.setImageResource(int Id);

【讨论】:

    猜你喜欢
    • 2015-03-03
    • 2013-03-09
    • 2013-12-21
    • 2014-04-11
    • 1970-01-01
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 2020-08-31
    相关资源
    最近更新 更多