我的情况是:我有一个按钮,可以用 SD 图像更改父布局的背景(这很好)。然后我喜欢将这些图像保存在 SharedPreference 中,以允许用户使用他们的背景图像而不是我的默认背景图像启动我的应用程序。我以这种方式保存图像:
SharedPreferences.Editor editor = prefs.edit();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
yourSelectedImage.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
editor.putString("background", Base64.encodeToString(b, Base64.DEFAULT ));
我以这种方式检索(此代码在 onCreate 中):
prefs = getSharedPreferences("Mis preferencias",Context.MODE_PRIVATE);
String fondo = prefs.getString("background", "vacio");
if(!fondo.equals("vacio")){
byte[] b = Base64.decode(fondo, Base64.DEFAULT);
InputStream is = new ByteArrayInputStream(b);
Bitmap yourSelectedImage = BitmapFactory.decodeStream(is);
BitmapDrawable bd = new BitmapDrawable(getResources(), yourSelectedImage);
View view = findViewById(R.id.padre);
view.setBackgroundDrawable(bd);
}
是第一次使用 sharedpreferences 并使用 base64 中的图像,所以我很少坚持这一点,如果我杀死我的应用程序并重新启动,则会出现默认背景,而不是自定义背景。有什么帮助吗?谢谢和对不起我的英语。