Android 在 View Pager 的 Parent Activity 片段中设置视图
Android Set views in fragment from Parent Activity in View Pager
我有一个 activity,它使用 ViewPager 和 FragmentPagerAdapter 来设置三个片段。现在,当 activity 加载时,我发出网络请求并计划根据网络回复更新三个片段中的视图。现在我很难从主要 activity 设置这些视图。我尝试过的事情(并且非常失败)是:
- 在FragmentClass中创建一个setter来设置视图数据。在片段
onViewCreated
方法中,我保存了文本视图的全局视图引用,然后尝试在网络负载时从 Activity 调用 setter。文本视图为 NULL,即在调用 setter 时甚至没有实例化。
- 在 Activity 中创建一个 getter 以从 Fragments
onViewCreated
method.But 中获取数据,在这种情况下,getter 不会找到作为网络的值请求未完成!
任何提示如何进行?我有三个具有相关数据的片段,想从一个点控制它们的视图设置。我不想从每个片段进行单独的网络调用。
- 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 上有很多很棒的答案)。
我有一个 activity,它使用 ViewPager 和 FragmentPagerAdapter 来设置三个片段。现在,当 activity 加载时,我发出网络请求并计划根据网络回复更新三个片段中的视图。现在我很难从主要 activity 设置这些视图。我尝试过的事情(并且非常失败)是:
- 在FragmentClass中创建一个setter来设置视图数据。在片段
onViewCreated
方法中,我保存了文本视图的全局视图引用,然后尝试在网络负载时从 Activity 调用 setter。文本视图为 NULL,即在调用 setter 时甚至没有实例化。 - 在 Activity 中创建一个 getter 以从 Fragments
onViewCreated
method.But 中获取数据,在这种情况下,getter 不会找到作为网络的值请求未完成!
任何提示如何进行?我有三个具有相关数据的片段,想从一个点控制它们的视图设置。我不想从每个片段进行单独的网络调用。
- 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 上有很多很棒的答案)。