如何在首选项中存储图像资源/名称

时间:2014-12-11 08:36:29

标签: android sharedpreferences r.java-file save-image

我有一个场景:

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

所以我的问题是我如何在偏好中保存它?保存图像的资源ID是否正确?一旦安装了应用程序,R.java内容是否保持相同?我只是不想在任何地方保存位图,因为它已经存在于drawable中。

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

3 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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);
}

答案 2 :(得分: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重新填充。