Android:从父片段引用子片段

时间:2014-11-19 10:19:28

标签: android android-fragments android-nested-fragment

我有嵌套片段方案。尝试从父片段引用子片段会给出null。我在这里缺少什么?

这是父片段的布局文件。

   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <!-- Statically nested fragment -->
    <fragment
        android:name="reports.fragments.fragments.usageBreakUp.fragments.Filter"
        android:id="@+id/fragment_filter"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

以下是我尝试从父片段

访问子片段的方法
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    Log.i(LOG_TAG, "ON VIEW CREATED");

    filter = (Filter) getChildFragmentManager().findFragmentById(R.id.fragment_filter);
    filter.populateStorageFilter(); // NPE here
}

2 个答案:

答案 0 :(得分:0)

你试过这个吗?

filter = (Filter) view.findViewById(R.id.fragment_filter);

答案 1 :(得分:0)

您可能会在populateStorageFilter内获得NPE,因为您的子片段onViewCreated尚未被调用,即子视图尚未初始化。因此,如果您在populateStorageFilter中使用任何视图引用,则它们为null。您必须等待子片段的视图创建,然后调用populateStorageFilter

相关问题