首页 > 解决方案 > Android studio kotlin,如何获取随机图像数组?

问题描述

我在drawable文件夹中有图像文件,命名如下:img1.png,img2.png,img3.png ... img16.png

有什么方法可以随机获取 5 张图像并将它们放入数组中?

标签: android-studiokotlin

解决方案


随机整数并获取可绘制资源IDResources#getIdentifier

 fun getDrawables(context: Context): Array<Drawable> {
        val imgIndices = ArrayList<Int>()
        val drawables = ArrayList<Drawable>()
        while (imgIndices.size < 5) {
            val index = Random.nextInt(16)
            if (!imgIndices.contains(index)) {
                imgIndices.add(index)
            }
        }
        for (i in imgIndices) {
            val drawableRes = context.resources.getIdentifier("img${i + 1}", "drawable", context.packageName)
            val drawable = ContextCompat.getDrawable(context, drawableRes)
            drawable?.let {
                drawables.add(it)
            }
        }
        return drawables.toTypedArray();
    }

推荐阅读