Android getParentFragment()在直接从布局中膨胀片段时为空

时间:2014-03-07 19:30:41

标签: android android-fragments fragmentmanager

我正在使用片段创建一个“动态”ui,与Android Building a Dynamic UI指南中的示例非常相似。不同之处在于我将两个片段包装在一个片段而不是活动中。

右侧窗格的布局大型布局文件类似于

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_message_multi_pane"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/some_color"
    android:baselineAligned="false"
    android:orientation="horizontal" >

    <fragment
        android:id="@+id/left_pane"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:name="com.rperryng.basicfragments.leftpane"

    <fragment
        android:id="@+id/right_pane"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="2"
        android:name="com.rperryng.basicfragments.rightpane"

</LinearLayout>

左窗格的onAttach()方法尝试调用mListener = (someInterface) getParentFragment()。但是,当布局使用大布局(即平板电脑)充气时,getParentFragment()调用为空(使用if语句和确认日志消息确认)。是什么赋予了?这是因为系统在直接从布局或其他东西中充气时没有使用childFragmentManager吗?我是否必须在运行时添加片段?值得注意的是我正在使用支持库

1 个答案:

答案 0 :(得分:3)

The Android Support Library also now supports nested fragments, so you
can implement nested fragment designs on Android 1.6 and higher.

Note: You cannot inflate a layout into a fragment when that layout includes a 
<fragment>. Nested fragments are only supported when added to a fragment dynamically.

在这里谈到http://developer.android.com/about/versions/android-4.2.html#NestedFragments