Android 在 View Pager 的 Parent Activity 片段中设置视图

Android Set views in fragment from Parent Activity in View Pager

我有一个 activity,它使用 ViewPager 和 FragmentPagerAdapter 来设置三个片段。现在,当 activity 加载时,我发出网络请求并计划根据网络回复更新三个片段中的视图。现在我很难从主要 activity 设置这些视图。我尝试过的事情(并且非常失败)是:

任何提示如何进行?我有三个具有相关数据的片段,想从一个点控制它们的视图设置。我不想从每个片段进行单独的网络调用。

  • Create a setter in Fragment Class to set the view data. In the fragment onViewCreated method I am saving global view references of textviews, and then try to call that setter from Activity on network load. The textviews are NULL, i.e not even instantiated when setter is called.

你做得对。

为什么那些文本视图有 NULL 值是关于您在调用 setter 方法时使用的片段引用。

简而言之:将此函数添加到您的 FragmentPagerAdapter 实现中

public Fragment getFragmentByPositionUsingTag(int position) {
    Fragment fragment = fm.findFragmentByTag("android:switcher:" + R.id.viewPager + ":" + position);

    return fragment;
}

并尝试使用它的引用 returns 来调用该方法。 (有关更多信息,SO 上有很多很棒的答案)。