方向更改后不会重新添加片段

时间:2012-10-25 08:57:53

标签: android android-fragments android-orientation

旋转设备时,我的应用中的片段不会重新添加到活动的视图中。如果我正确理解文档(以及SO上的类似问题),这应该是片段管理器处理的(不需要在我的清单中指定android:configChanges)。

我的活动如下:

public class MainActivity extends SherlockFragmentActivity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        if (savedInstanceState == null){
            getSupportFragmentManager().beginTransaction()
                .add(R.id.main_fragment_placeholder, new DashboardFragment(),"dashboard")
                .commit();
        }
    }
}

片段看起来像(为了清楚起见,省略了clicklisteners等等):

public class DashboardFragment extends SherlockFragment {
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_dashboard, container, false);
    }
}

布局文件看起来像(activity_main.xml):

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:id="@+id/main.main">

    <FrameLayout android:id="@+id/main_fragment_placeholder"
             android:layout_height="fill_parent"
             android:layout_weight="1"
             android:layout_width="0px"
             />

</LinearLayout>

和fragment_layout.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main.wrapper"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <my.layout.DashboardLayout
           android:layout_width="fill_parent"
           android:layout_height="fill_parent"
           android:id="@+id/main.dashboard">
    <!-- some buttons here -->
    </my.layout.DashboardLayout>

</LinearLayout>

但是,当我旋转设备时,屏幕始终变为空白。

2 个答案:

答案 0 :(得分:11)

原来我做了一件愚蠢的事。我在我的活动中覆盖了onSaveInstanceState(...)方法,而没有调用super.onSaveInstanceState(),导致片段无法重新创建。在这里发布答案,希望我可以节省别人的时间!

答案 1 :(得分:0)

通常会在配置更改时重新创建片段。如果您不希望发生这种情况,请使用

Fragment的构造函数中的

setRetainInstance(true);

这将导致在配置更改期间保留片段。

http://developer.android.com/reference/android/app/Fragment.html#setRetainInstance(boolean

相关问题