【问题标题】:Android : Referencing child fragment from parent fragmentAndroid:从父片段引用子片段
【发布时间】:2014-11-19 10:19:28
【问题描述】:

我有嵌套片段场景。尝试从父片段引用子片段会给出空值。我在这里错过了什么?

这是父片段的布局文件。

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

【问题讨论】:

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


    【解决方案1】:

    你试过了吗

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-03-18
        • 2019-03-17
        • 1970-01-01
        • 2018-03-20
        • 1970-01-01
        • 2018-06-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多