问题描述
我有一个活动,叫的setContentView与该XML:
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延伸片段,一切都很好那里。不过,我将展示从内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,字符串)?
What's the proper way to display a DialogFragment from within another Fragment other than DialogFragment.show(FragmentManager, String)?
推荐答案
确定,而Zsombor的方法的工作,这是由于我是没有经验与片段和他的解决方案,使得与 saveInstanceState捆绑问题code>。
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),它应该是一个公共静态类
。您还必须编写自己的静态DialogFragment的newInstance()
方法。这是因为碎片类调用它的实例化
方法。的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.
这篇关于片段,DialogFragment,以及屏幕旋转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!