繁体   English   中英

Android:从父片段引用子片段

[英]Android : Referencing child fragment from parent fragment

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

这是父片段的布局文件。

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

你尝试过这个吗

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM