我正在开发一个Android应用程序,我在页面上有一个imageView,并且在长按时它从图像A更改为图像B。但是,当他们离开页面时,imageView返回到图像A。我如何保存状态(我猜测它已完成暂停、停止和销毁),以便保存 ImageView 的当前图像 src 并在下次访问和创建页面时加载它。我从来没有在Android中做过数据保存..
任何简单的数据保存教程/示例将不胜感激。
最佳答案
以下内容应该可以帮助您:
// Use a static tag so you're never debugging typos
private static final String IMAGE_RESOURCE = "image-resource";
private int image;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// if there's no bundle, this is the first time; use default resource
if (savedInstanceState == null) {
image = R.drawable.default;
} else {
// if there is a bundle, use the saved image resource (if one is there)
image = savedInstanceState.getInt(IMAGE_RESOURCE, R.drawable.default);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
// Make sure you save the current image resource
outState.putInt(IMAGE_RESOURCE, image);
super.onSaveInstanceState(outState);
}
确保在点击监听器中更改图像变量的同时将图像变量设置为正确的资源。
如果您希望记住该状态的时间比这更长,请查看 SharedPreferences .
关于android - 动态更改 src 后保存 Android 图像状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10875602/