简体   繁体   English

Android在View Pager的父活动中设置片段视图

[英]Android Set views in fragment from Parent Activity in View Pager

I have an activity which uses ViewPager and FragmentPagerAdapter to setup three fragments. 我有一个使用ViewPager和FragmentPagerAdapter来设置三个片段的活动。 Now when the activity loads, I issue a network request and plan to update the views in three fragments on reply from network. 现在,当活动加载时,我发出网络请求,并计划在收到网络答复时分三部分更新视图。 Now I am having difficulty to set those views from the main activity. 现在,我很难从主要活动中设置这些视图。 Things I have tried (and spectacularly failed) are : 我尝试过的事情(并且失败了):

  • Create a setter in Fragment Class to set the view data. 在“片段类”中创建一个setter来设置视图数据。 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. 在片段onViewCreated方法中,我保存了textview的全局视图引用,然后尝试在网络负载时从Activity调用该setter。 The textviews are NULL, ie not even instantiated when setter is called. 文本视图为NULL,即在调用setter时不实例化。
  • Create a getter in Activity to get the data from Fragments onViewCreated method.But in this case, the getter wont find the values as network request is not complete! 在Activity中创建一个getter以从Fragments onViewCreated获取数据。 onViewCreated在这种情况下,由于网络请求未完成,getter不会找到这些值!

Any tips how to proceed? 任何提示如何进行? I have three fragments with related data and want to control their view settings from a single point. 我有三个带有相关数据的片段,希望从一个角度控制它们的视图设置。 I dont want to make separate network calls from each Fragment. 我不想从每个Fragment进行单独的网络调用。

  • Create a setter in Fragment Class to set the view data. 在“片段类”中创建一个setter来设置视图数据。 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. 在片段onViewCreated方法中,我保存了textview的全局视图引用,然后尝试在网络负载时从Activity调用该setter。 The textviews are NULL, ie not even instantiated when setter is called. 文本视图为NULL,即在调用setter时不实例化。

You're doing it right. 您做对了。

Why do those textviews have NULL value is all about a fragment reference you use when you call the setter method. 为什么这些textview具有NULL值,这全都与调用setter方法时使用的片段引用有关。

In short: add this function to your FragmentPagerAdapter implementation 简而言之:将此函数添加到FragmentPagerAdapter实现中

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

    return fragment;
}

and try to use the reference it returns to call the method. 并尝试使用它返回的引用来调用该方法。 (For more information there are many great answers on SO). (有关更多信息,SO上有很多不错的答案)。

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

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