android-studio - Android studio kotlin,如何获取随机图像数组?
问题描述
我在drawable文件夹中有图像文件,命名如下:img1.png,img2.png,img3.png ... img16.png
有什么方法可以随机获取 5 张图像并将它们放入数组中?
解决方案
随机整数并获取可绘制资源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();
}
推荐阅读
- python-3.x - Flask 中的散景小部件
- python - 如何将此直方图中的蓝条放在前面?
- python - 在 Redshift 上运行 python cursor.execute for UNLOAD 命令时获取行数
- laravel - 如何在 Laravel Cashier 中进行计量订阅?
- java - 使用 Arraylist 附加序列
- c++ - 返回一个空字符串文字 VS。返回一个 nullptr - 它们是一样的吗?
- python - Pandas 在 Azure Databricks Notebook 中缺少 read_parquet 函数
- java - 以编程方式在编辑器中打开文件:org.eclipse.ui.PartInitException:无法初始化编辑器
- python - 第一个 tensorflow 训练步骤比其他任何步骤都需要更长的时间
- sql - 如何在没有 lua 的情况下对 Redis 密钥进行 100% 确定的条件更新?