【问题标题】:Saving Android image state after dynamically changing the src动态更改 src 后保存 Android 图像状态
【发布时间】:2012-06-04 02:09:54
【问题描述】:

我正在开发一个 Android 应用程序,我在页面上有一个 imageView,onLongClick 它从 Image A 更改为 Image B。但是,当他们离开页面时,imageView 又回到 Image A。我如何保存状态(我猜它已经完成了暂停、停止和销毁),以便它保存 ImageView 的当前图像 src 并在下次访问和创建页面时加载它。我从来没有在 Android 中保存过数据..

任何简单的数据保存教程/示例将不胜感激。

【问题讨论】:

    标签: android imageview onrestoreinstancestate


    【解决方案1】:

    这些方面的东西应该可以帮助你:

    // 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

    【讨论】:

    • 嗨 Krylez,如果应用程序完全关闭或者他们点击返回按钮退出活动。这仍然会检索数据吗?我的意思是,当然,如果我在 onDestroy / onStop 等上进行调用,或者当应用程序关闭时,savedinstancestate 会丢失数据
    • 当您关闭应用程序时,捆绑软件会丢失。它只存在于内存中,因此当 Android 操作系统关闭您的应用程序时,它就永远消失了。即使您的应用关闭,SharedPreferences 也会保留。
    • 谢谢。我想我需要使用 SharedPreferences。
    猜你喜欢
    • 2023-04-02
    • 1970-01-01
    • 2016-02-13
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    • 2016-07-10
    • 1970-01-01
    • 2014-05-16
    相关资源
    最近更新 更多