Fragments、DialogFragment 和屏幕旋转 [英] Fragments, DialogFragment, and Screen Rotation

查看:21
本文介绍了Fragments、DialogFragment 和屏幕旋转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用此 XML 调用 setContentView 的活动:

I have an Activity that calls setContentView with this XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    >
    <fragment android:name="org.vt.indiatab.GroupFragment"
        android:id="@+id/home_groups"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1" />
            <..some other fragments ...>
</LinearLayout>

GroupFragment 扩展了 Fragment,一切都很好.但是,我从 GroupFragment 中显示了一个 DialogFragment.这显示正确,但是当屏幕旋转时,我得到了强制关闭.

The GroupFragment extends Fragment, and all is well there. However, I show a DialogFragment from within GroupFragment. This shows correctly, HOWEVER when the screen rotates, I get a Force Close.

从 DialogFragment.show(FragmentManager, String) 以外的另一个 Fragment 中显示 DialogFragment 的正确方法是什么?

What's the proper way to display a DialogFragment from within another Fragment other than DialogFragment.show(FragmentManager, String)?

推荐答案

好的,虽然 Zsombor 的方法有效,但这是因为我对 Fragments 缺乏经验,而他的解决方案导致 saveInstanceState Bundle 出现问题.

OK, while Zsombor's method works, this is due to me being inexperienced with Fragments and his solution causes issues with the saveInstanceState Bundle.

显然(至少对于DialogFragment),它应该是一个public static class.您还必须编写自己的 static DialogFragment newInstance() 方法.这是因为 Fragment 类在其 instantiate() 方法中调用了 newInstance 方法.

Apparently (at least for a DialogFragment), it should be a public static class. You also MUST write your own static DialogFragment newInstance() method. This is because the Fragment class calls the newInstance method in its instantiate() method.

总之,您必须像这样编写 DialogFragments:

So in conclusion, you MUST write your DialogFragments like so:

public static class MyDialogFragment extends DialogFragment {

    static MyDialogFragment newInstance() {
        MyDialogFragment d = new MyDialogFragment();
        return d;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        ...
    }
}

并向他们展示:

private void showMyDialog() {
    MyDialogFragment d = MyDialogFragment.newInstance();
    d.show(getFragmentManager(), "dialog");
}

这可能是 ActionBarSherlock 库独有的,但 SDK 文档中的官方示例也使用此范例.

This may be unique to the ActionBarSherlock Library, but the official samples in the SDK documentation use this paradigm also.

这篇关于Fragments、DialogFragment 和屏幕旋转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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