我正在使用SharedPreferences將一組 Drawables 保存為 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
如何遍歷 mySharedPreferences以生成 Drawable 檔案名陣列,而不是資源的 Int 表示?
uj5u.com熱心網友回復:
要遍歷 int 陣列并將它們轉換為字串,您可以使用map函式:
val imagesFromSaved = PrefsContext(context).savedLocations
val imagesNames: List<String> = imagesFromSaved.map {
context.getResources().getResourceEntryName(it)
}
map將物件串列轉換為另一種型別的物件串列。結果imagesNames應包含影像的名稱。
uj5u.com熱心網友回復:
根據你的描述,我建議你應該這樣做:
- 首先,保存 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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/397327.html
