作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的应用程序中有一系列 ImageButtons。通过该应用程序,用户可以将 ImageButton 的背景设置为可绘制文件。这工作得很好,当用户选择他们想要的图像并单击刷新按钮时,ImageButton 的图像会发生变化。
问题是,当我转到其他 Activity 时,更改后的 ImageButton 会返回到默认图像。
我一直在尝试通过 SharedPreferences 来做到这一点。我尝试使用此处的所有其他类似问题来解决此问题,但没有成功。
当谈到 SharedPreferences 时,我是一个完全的初学者,我知道存储图像不是它的目的,但这是我能想到的解决问题的唯一方法。
任何帮助将极大感激!预先感谢各位。
我对使用 SharedPreferences 存储图像的了解:我知道我必须将可绘制对象转换为位图,然后将其编码为 Base64(因为 SharedPreferences 将接受字符串)。我已经做到了这一点,并且我认为编码正在工作。
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
grey11.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] grey11base64 = byteArrayOutputStream.toByteArray();
final String encodedGrey11 = Base64.encodeToString(grey11base64, Base64.DEFAULT);
在我的主要 Activity (显示图像的位置)中,我当前有 OnCreate 和 onStop 方法以及用于刷新按钮的 onClick。
编辑:
在我的 onCreate(Bundle savingInstantState) 中:
final SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("drawableAgreen", R.drawable.a);
editor.commit();
在我的刷新按钮内:
int drawableId = sharedPref.getInt("drawableId", 0);
ImageButton.setBackgroundResource(drawableId)
最佳答案
只需将可绘制 ID 存储在 SharedPreferences 中并引用即可。
// store drawable id in SharedPreferences
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("drawableId", R.drawable.btn_background);
editor.commit();
// Read from sharedPref and set background
int drawableId = sharedPref.getInt("drawableId", 0);
ImageButton imageButton = (ImageButton) findViewById(R.id.imageButton);
imageButton.setBackgroundResource(drawableId);
关于java - 如何在SharedPreferences中保存ImageButton的资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43622571/
我是一名优秀的程序员,十分优秀!