Android studio Android studio kotlin,如何获得随机图像数组?

Android studio Android studio kotlin,如何获得随机图像数组?,android-studio,kotlin,Android Studio,Kotlin,我在drawable文件夹中有图像文件,名称如下: img1.png,img2.png,img3.png。。。img16.png 有没有办法随机获得5张图像并将它们放入数组 定义可提取列表 随机指数 将索引转换为可绘制索引 随机整数并使用Resources\getIdentifier fun getDrawables(context: Context): Array<Drawable> { val imgIndices = ArrayList<Int>(

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

有没有办法随机获得5张图像并将它们放入数组

  • 定义可提取列表
  • 随机指数
  • 将索引转换为可绘制索引

  • 随机整数并使用
    Resources\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();
        }
    
    有趣的getDrawables(context:context):数组{ val imgIndices=ArrayList() val drawables=ArrayList() 而(imgIndices.size<5){ val索引=随机.nextInt(16) 如果(!imgIndices.contains(index)){ imgIndices.add(索引) } } 对于(i在imgIndices中){ val drawableRes=context.resources.getIdentifier(“img${i+1}”,“drawable”,context.packageName) val drawable=ContextCompat.getDrawable(context,drawableRes) 可抽出的?让我来{ drawables.添加(it) } } 返回drawables.toTypedArray(); }
    您能否在所需范围内生成适当数量的随机数,使用字符串插值创建文件名,从文件名创建图像,然后将它们放入数组中?如果这不是你想要的,也许你可以指定你被困在流程的哪一部分。
     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();
        }