【问题标题】:Converting an int array of Drawable images to a string array of their filenames将可绘制图像的 int 数组转换为其文件名的字符串数组
【发布时间】:2021-12-29 01:10:44
【问题描述】:

我正在使用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 以生成一个可绘制文件名数组,而不是资源的 Int 表示?

【问题讨论】:

  • 您需要 resources.getResourceEntryName() 函数。
  • @MikeM。我是否只需使用 for 循环从 imagesFromSaved 创建新的字符串数组?
  • 对不起,我没有意识到循环是未知的一部分。 Sergey 在下面的回答中有一个恰当的例子。

标签: android arrays loops kotlin sharedpreferences


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    根据你的描述,我建议你应该这样做:

    • 首先,保存你的描述文件名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)
    

    【讨论】:

    • 感谢您的回答。看起来我只需要使用 getResourceEntryName 函数将我的 Int 数组简单地转换为字符串数组。现在正在努力解决这个问题。
    猜你喜欢
    • 2012-03-26
    • 1970-01-01
    • 2021-12-21
    • 2016-08-14
    • 1970-01-01
    • 1970-01-01
    • 2016-01-27
    • 2013-05-31
    • 2018-11-09
    相关资源
    最近更新 更多