getLastNonConfigurationInstance() [英] getLastNonConfigurationInstance()

查看:258
本文介绍了getLastNonConfigurationInstance()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

长话短说,我要开发一个小型应用程序显示一个随机图像的应用程序启动时。我很快发现,当设备方向改变,主要活动重新装入一个新的形象被选中。有人在这个网站帮我宣布一个空图像的OnCreate()那么,和里面的的OnCreate()我有这样的:

Long story short, I have to develop a small application that displays a random image when the app launches. I discovered quickly that when the device orientation changed, the main activity re loaded and a new image was chosen. Someone on this site helped me solve this by declaring a null image outside of OnCreate(), and then inside of OnCreate() I have this:

image = (Bitmap) getLastNonConfigurationInstance();

    if (image == null) {
        image = getRandomImage();
    }
    setRandomImage(image);

这工作得很好。我现在的问题是,我必须添加到应用程序随机每日新闻,我不能做这项工作。当设备方向改变一个新的报价被牵引。我想,也许下面的工作,但它并不:

This works nicely. My problem now is that I have to add a random "quote of the day" to the app and I can't make this work. A new quote is being pulled when the device orientation changes. I thought that maybe the following would work, but it doesn't:

message = (String) getLastNonConfigurationInstance();

    if (message == null) {
        message = getRandomMessage();
    }
    setRandomMessage(message);

我可能只是不理解如何 getLastNonConfigurationInstance()的作品,因此,如果有人可以帮助我我最好的AP preciate吧。

I'm probably just not understanding how getLastNonConfigurationInstance() works, so if someone could help me out I'd appreciate it.

推荐答案

<一个href="http://developer.android.com/reference/android/app/Activity.html#getLastNonConfigurationInstance%28%29"><$c$c>getLastNonConfigurationInstance()会给你对象,是由 onRetainNonConfigurationInstance()

您只能保存/检索一个对象与此机制。所以,只要包装到另外两个类的信息和图像,并使用它。

You can only save/retrieve one Object with this mechanism. So, just wrap both message and image in another class and use that.

更新:

public class ConfigWrapper{
    public Bitmap image;
    public String message;
}

然后使用它:

then use it:

ConfigWrapper config = (ConfigWrapper) getLastNonConfigurationInstance();

if(config == null || config.image == null ){ 
    image = getRandomImage();
} else {
    image = config.image;
}
setRandomImage(image);

然后创建在配置你的 onRetainNonConfigurationInstance()

onRetainNonConfigurationInstance(){
     ConfigWrapper config = new ConfigWrapper();
     config.image = // get last image from where you have it
     config.message = // get last message 
     return config;
}

这篇关于getLastNonConfigurationInstance()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆