1

我有一个场景:

假设有两个图像一个.png和两个.png。用户必须选择一个图像,我必须在首选项中保存图像的名称资源 ID。稍后当用户打开应用程序时,我将加载用户上次选择的图像。

所以我的问题是我将如何将其保存在首选项中?为图像保存资源 ID 是否正确?安装应用程序后,R.java 内容是否保持不变?我只是不想将位图保存在任何地方,因为它已经存在于可绘制对象中。

请帮我理清我的概念。谢谢。

4

3 回答 3

3

您应该保存名称,即(一,二在您的情况下)

稍后,您可以通过名称获取资源的 ID

String imageNameFromPreferences= getLastUsedImageFromPref();
//get resource id by name
final int resourceIdOfLastUsedImage = resources.getIdentifier(imageNameFromPreferences, "drawable", 
   context.getPackageName());
//use this id to set the image anywhere
imageView.setBackgroundResource(resourceIdOfLastUsedImage)
于 2014-12-11T08:47:19.453 回答
1

我只想保存一个提示上次显示哪个图像。我会使用“img1”和“img2”之类的东西。然后下次在 onCreate 加载正确的图像。一般来说,保存资源 id 应该可以正常工作,但是如果您添加和删除新图像,​​则 id 可能会更改。但是,这只能在更新后发生。

onCreate在您的方法中尝试此代码:

SharedPreferences prefs = context.getSharedPreferences(BuildConfig.APPLICATION_ID + "_preferences", Context.MODE_PRIVATE);
String lastImg = settings.getString("image");
if("img1".equals(lastImg) {
    imageView.setDrawable(R.drawable.img1);
} else if("img2".equals(lastImg) {
    imageView.setDrawable(R.drawable.img2);
}
于 2014-12-11T08:46:43.360 回答
0

做这样的事情:

public List<Integer> myImagesList;

public void createMyImagesList{
    //Here put all the image ids you need into the list
    myImagesList.put(R.id.one);
    myImagesList.put(R.id.two);
} 

之后,当您要存储用户选择时,只需存储所选图像的列表位置即可。

public Integer obtainUserSelectedImage(int theIdStoredInPrefs){
    return myImageList.get(theIdStoredInPrefs);
}

通过这种方式,您可以创建一个独立于 R.drawable id 的包装器 id,因为每次重新运行应用程序(并且可能重新构建)时,列表将重新填充有效的 id。

于 2014-12-11T08:41:13.573 回答