设备旋转后不显示DialogFragment与setRetainInstanceState(真) [英] DialogFragment with setRetainInstanceState(true) is not displayed after the device is rotated

查看:523
本文介绍了设备旋转后不显示DialogFragment与setRetainInstanceState(真)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于DialogFragment的问题。我试图使该器件保持旋转后的状态的对话框。这个对话框有一堆提到的东西,如适配器和其他更重的物体,我想这能保持在旋转时,如果可能的话,而不必让每一个参考Parcelable或序列化,以便我使用的onSaveInstanceState保存和何时恢复它们原来的活动是重新创建。

I have a question regarding DialogFragment. I am trying to make a dialog that keeps it's state after the device is rotated. This dialog has a bunch of references to things such as adapters and other heavier objects and I need this to be kept upon rotation, if possible without having to make every reference Parcelable or Serializable in order for me to use onSaveInstanceState to save and restore them when the original activity is re-created.

我注意到有一个在DialogFragment称为setRetainInstance(布尔)一种方法,它可以让你保持对话片段实例重新创建的活动时。然而,当我现在旋转装置,该对话框不显示了。我知道我可以从活动的FragmentManager得到它,但我不能找到一种方法,使其再次可见。在这个有什么建议?

I've noticed there's a method called setRetainInstance(boolean) on the DialogFragment which allows you to keep the dialog fragment instance when the activity is re-created. However, when I rotate the device now, the dialog is not showing anymore. I know I can get it from the activity's FragmentManager, but I cannot find a way to make it visible again. Any suggestions on this?

谢谢, 米哈伊

推荐答案

有几件事情你需要做的:

There are few things you need to do :

  1. 使用实例工厂方法来启动一个DialogFragment实例是这样的:

  1. use instance factory method to initiate a DialogFragment instance like this :

public static MyDialogFragment newInstance(MyModel model) {
    MyDialogFragment myDialogFragment = new MyDialogFragment();
    Bundle bundle = new Bundle();
    bundle.putSerializable("MODEL", model);
    myDialogFragment .setArguments(bundle);
    return myDialogFragment;
}

  • 通过将setRetainInstance(真)在的onCreate,所有在片段中声明将保留原来的活动后,您引用的是重新创建

  • by putting setRetainInstance(true) in onCreate, all of your references declared in the fragment will be kept after the original activity is re-created

    @Override
    public void onCreate(Bundle icicle) {
        this.setCancelable(true);
        setRetainInstance(true);
        super.onCreate(icicle);
    
    }
    

  • 避免了这样消失在转动

  • avoiding disappear on rotation by doing this

    @Override
    public void onDestroyView() {
        if (getDialog() != null && getRetainInstance())
            getDialog().setDismissMessage(null);
        super.onDestroyView();
    

    }

    使用让您的对象

    (MyModel) getArguments().getSerializable("MODEL")
    

  • 这篇关于设备旋转后不显示DialogFragment与setRetainInstanceState(真)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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