【问题标题】:Using a Random Number in a Drawable Path在可绘制路径中使用随机数
【发布时间】:2013-06-21 10:15:48
【问题描述】:

我正在使用随机数将我的 imageButton 设置为随机图像。我想知道是否有办法在drawable的文件路径中使用随机int。此代码给出了无效整数的运行时错误,但会编译。

Random generator = new Random();
int chooseFirstPicture = generator.nextInt(2);
int imagePath1 = Integer.parseInt("R.drawable.image" + chooseFirstPicture);
btn1.setBackgroundResource(imagePath1);

【问题讨论】:

    标签: android random path numbers drawable


    【解决方案1】:

    您将String 解析为Integer,因此您的代码每次运行时都会抛出NumberFormatException

    从字符串键中获取资源id的正确方法是使用函数getIdentifier():

    Random generator = new Random();
    int chooseFirstPicture = generator.nextInt(2);
    int resourceId = getResources().getIdentifier("image" + chooseFirstPicture, "drawable", getPackageName());
    if (resourceId != 0) {
        //Provided resource id exists in "drawable" folder
        btn1.setBackgroundResource(imagePath1);
    } else {
        //Provided resource id is not in "drawable" folder.
        //You can set a default image or keep the previous one.
    }
    

    您可以在 Android Resources class 文档中找到更多信息。

    【讨论】:

    • 这就是我要找的,谢谢!
    【解决方案2】:

    嗯..您试图将“R.drawable.image1”字符串转换为不可能的整数。在编译过程中,不会检查字符串中的内容,但是当您运行应用程序时,它会立即失败。

    最好使用带有适当参数的 getResources().getIdentifier() (link)

    希望对你有帮助:)

    【讨论】:

    • "R.drawable.image1" 不能转换成整数?因为 setBackgroundResource() 方法接受一个整数并且当我直接将图像路径放入它的参数时起作用(setBackgroundResource(R.drawable.image1))。
    • R.drawable.image != "R.drawable.image1"
    猜你喜欢
    • 1970-01-01
    • 2017-01-09
    • 2015-10-24
    • 2012-03-16
    • 1970-01-01
    • 1970-01-01
    • 2016-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多