将 Drawable 图像的 int 数组转换为其文件名的字符串数组

Converting an int array of Drawable images to a string array of their filenames

我正在使用 SharedPreferences 将 Drawable 数组保存为 Int(稍后用于设置 setImageResource

我需要在 SharedPreferences 上执行一些逻辑, 需要 我获取实际的文件名,而不是可绘制对象的 Int 表示。

我的代码如下:

val imagesFromSaved = PrefsContext(context).savedLocations

imagesFromSaved 打印以下内容:

[2131135903, 2131165414, 2134135800, 2131765348]

我需要能够打印实际的文件名。像这样。

["image_one", "image_two", "image_three", "image_four"]

我得到的最接近的结果是使用 getString 和一个单曲 Int。但我不确定如何遍历数组中的所有项目以将所有内容转换为字符串表示形式。

val test = context.resources.getString(2131135903)

打印:res/drawable-nodpi-v4/image_one.webp

如何遍历我的 SharedPreferences 以生成一个 Drawable 文件名数组,而不是资源的 Int 表示形式?

根据您的描述,我建议您做如下处理:

  • 首先,保存作为您的描述文件名的str
  • 然后从 sp
  • 中获取文件名
  • 最后还是得用str来生成drawable id
//get the R.draw.fileName,it result is fileName
val fileName = context.getResources().getResourceEntryName(R.drawable.arrow_back)

// then use SharedPreferences get the  str, To generate ID
val id = context.getResources().getIdentifier(fileName, "drawable", context.getPackageName());

// then use the id in imageView
imegeView.setImageResource(id)

要遍历 int 数组并将它们转换为字符串,您可以使用 map 函数:

val imagesFromSaved = PrefsContext(context).savedLocations
val imagesNames: List<String> = imagesFromSaved.map {
    context.getResources().getResourceEntryName(it)
}

map 将对象列表转换为另一种类型的对象列表。 结果 imagesNames 应该包含图像的名称。