方向从双窗格更改为单窗格

时间:2012-09-12 15:10:46

标签: android android-fragments android-orientation

横向和纵向的不同布局之间的方向变化似乎很容易,但是我无法找到解决当前情况的方法。

我想在横向模式中使用带有两个片段的双窗格布局

RES \布局陆\ dashboard_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <fragment class="xxx.DashboardFragment"
            android:id="@+id/master_frag"
            android:layout_width="@dimen/timeline_size"
            android:layout_height="match_parent"/>

    <fragment class="xxx.TaskInstanceFragment"
            android:id="@+id/details_frag"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
</LinearLayout>

和纵向模式下的单窗格布局

RES \布局\ dashboard_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <fragment class="xxx.DashboardFragment"
        android:id="@+id/master_frag"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

</FrameLayout>

我想要注意DashboardFragment包含一个ViewPager。不知道它是否重要。

现在,当我将方向从横向(双重)更改为纵向(单个)时,应用程序崩溃,因为它想要更新details_frag。当我以肖像方式开始活动时,它起作用,只有从横向切换到肖像会产生问题。

在活动中有以下代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.dashboard_activity);

    Fragment frag = getSupportFragmentManager().findFragmentById(R.id.details_frag);
    mDualFragments = frag != null;

    /* .. */
}

现在FragmentManager仍然在我切换到纵向模式时找到详细信息片段,因此mDualFragments仍然是真的但应该是假的,这导致稍后调用细节片段中的方法。

那么,为什么呢? :)

此致 Konsumierer

1 个答案:

答案 0 :(得分:5)

因为findFragmentById不仅返回当前布局中的片段,还返回先前显示的片段。试试这个:

mDualFragments = frag != null && frag.isInLayout();