Android getParentFragment() 直接从布局中膨胀 fragment 时为空

标签 android android-fragments fragmentmanager

我正在创建一个带有 fragment 的“动态”用户界面,与 Android 的 Building a Dynamic UI 中的示例非常相似指导。不同之处在于我将两个 fragment 包装在一个 fragment 中而不是 Activity 中。

右侧 Pane 的布局大布局文件如下所示

<?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>

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

最佳答案

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

关于Android getParentFragment() 直接从布局中膨胀 fragment 时为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22259043/

相关文章:

android - getSupportFragmentManager() 上的 NullPointerException

java - Kotlin - list 合并失败 : Attribute application@appComponentFactory

java - NullPointerException 在 onCreate() 中访问 View

android - 将数据从当前 fragment 传回前一个 fragment

android - Fragment不调用OnCreate方法

android - 多个 fragment 的 TreeView

java.lang.IllegalStateException : FragmentManager has been destroyed

安卓/ eclipse : How to change project name on import?

Android Activity 和服务关系

android - 模块是使用不兼容的 Kotlin 版本编译的。其元数据的二进制版本是 1.5.1,预期版本是 1.1.15