android - 动态更改 src 后保存 Android 图像状态

标签 android imageview onrestoreinstancestate

我正在开发一个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/

相关文章:

android - 长时间处于后台后应用程序崩溃

Android Activity 生命周期

Android 位图工厂内存不足第二张照片

android - 如何从首选项屏幕打开 AlertDialog?

android - 无法在低于 16 的 Android API 上调整 ImageView

android - 安卓真机和模拟器图片显示不同

android - 验证时出现 Firebase .getUID NullPointerException

java - 以编程方式在 fragment 中包含 View 中的布局

android - 设置图片边框突然出现问题

android - 保存 RecyclerView 列表状态