简体   繁体   English

从FragmentPagerAdapter中的片段更新活动标题

[英]Update Activity title from fragment in FragmentPagerAdapter

I have v4.ViewPager inside Activity and use SlidingTabLayout from google's examples SlidingTabBasics. 我有v4.ViewPagerActivity ,并使用SlidingTabLayout从谷歌的例子SlidingTabBasics。 The problem I encounter is that each fragment retrieved from getItem(position) in v4.FragmentPagerAdapter has to refresh activity title . 我遇到的问题是,从v4.FragmentPagerAdapter getItem(position)检索到的每个片段都必须刷新活动title I have already learnt the hard way that FragmentPagerAdapter causes fragments to have really weird life callbacks so I can't probably use onResume or onStart . 我已经了解了FragmentPagerAdapter导致片段具有异常怪异的生命回调的困难方法,因此我可能无法使用onResumeonStart I noticed though that onCreateOptionsMenu(menu,inflater) gets called exactly when I want to refresh activity title. 我注意到,当我想刷新活动标题时onCreateOptionsMenu(menu,inflater)会调用onCreateOptionsMenu(menu,inflater) Is there a callback to supply actions when ViewPager has settled the fragment and it should change activity title? ViewPager解决了片段并且应该更改活动标题时,是否存在提供操作的回调? Setting callback on ViewPager.onPageSelected(position) is inconvenient because I want this information to be propagated from fragment, not to fragment. ViewPager.onPageSelected(position)上设置回调ViewPager.onPageSelected(position)方便,因为我希望此信息片段而不是片段传播。

Currently I 'steal' onCreateOptionsMenu(menu,inflater) to do the work for me but it causes optimisation issues when no menu should be inflated but I still want the fragment to be able to affect activity title. 目前,我“窃取” onCreateOptionsMenu(menu,inflater)为我完成工作,但是当不应该夸大菜单但我仍然希望该片段能够影响活动标题时,这会导致优化问题。

Have you tried this code in your fragment: 您是否在片段中尝试过此代码:

if(getActivity() != null){
   getActivity().setTitle("new title");
}

Take into consideration that getActivity() will be null if the fragment is not yet attached to the activity. 请注意,如果片段尚未附加到活动,则getActivity()将为null。

Godspeed. 一帆风顺。

You can do this in different ways. 您可以通过不同的方式执行此操作。 You can use interfaces in fragments that can be implemented by activity. 您可以在可以按活动实现的片段中使用接口。 But the drawback is, if you do have large number of fragments you must implement all of them. 但是缺点是,如果确实有大量片段,则必须实现所有片段。

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

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