【发布时间】:2021-08-24 15:25:28
【问题描述】:
我正在开发一个应用程序,它需要从我的 drawables 文件夹在手机上设置一些壁纸,但我必须为每个文件分别编写代码。这是我的代码:
fun setWallpaper(number:Int) {
val wallpaperManager = WallpaperManager.getInstance(context)
val i: Int = when(number){
0->R.drawable.wp1.toInt()
1->R.drawable.wp2.toInt()
2->R.drawable.wp3.toInt()
3->R.drawable.wp4.toInt()
4->R.drawable.wp5.toInt()
5->R.drawable.wp6.toInt()
6->R.drawable.wp7.toInt()
7->R.drawable.wp8.toInt()
8->R.drawable.wp9.toInt()
9->R.drawable.wp10.toInt()
else->0
}
wallpaperManager.setResource(i)
}
数字变量是我从recyclerview 得到的位置。但这似乎不是一个好方法而且不是动态的,当我有 100 个左右的文件时,我无法为每个文件编写一行代码 有没有一种方法可以用来将变量连接到文件名?我该怎么做? 非常感谢
【问题讨论】:
-
我更新了我的答案以更完整。如果您有很多文件,您可能会更喜欢另一种方式。