我在我的应用中使用了SlidingTabLayout
(来自Google来源)在不同片段之间导航。 我可以在内容之间滑动很好,但是我面临的问题是行为栏的标题奇怪。SlidingTabLayout和Actionbar标题
假设我有两个标签有两个头衔(“第一名称”和“第二名称”):
| Action bar |
| First Title | Second Title |
当我第一次进入包含SlidingTabLayout
的片段,其在动作条的标题是这样的:
| Firs... |
| First Title | Second Title |
当我刷卡(到例如第二个选项卡),所述动作条的标题变为:
| Second Title |
| First Title | Second Title |
并保持这样的状态。当我滑动至少一次时,似乎操作栏将加载最后一个片段的标题。
我想是这样的:
我想在动作条永远不会改变,无论在SlidingTabLayout
标题就是显示一个“主标题”。
下面是我的代码的一些部分:
**含有SlidingTabLayout片段:
private String mainTitle;
....
@Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
// The mainTitle is given to this fragment by another fragment
Bundle args = getArguments();
if (args != null) {
mainTitle = args.getString("TITLE");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.layout, container, false);
mViewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
mSlidingLayout = (SlidingTabLayout) rootView.findViewById(R.id.sliding_layout);
List<Fragment> listFragments = new ArrayList<>();
List<String> listTitles = new ArrayList<>();
for (int i = 0; i < mSize; i++) {
Bundle bundle = new Bundle();
....
listFragments.add(Fragment.instanciate(getActivity(), CustomFragment.class.getName(), bundle));
listTitles.add("...");
}
mViewPager.setAdapter(new PagerAdapter(getChildFragmentManager(), listFragments, listTitles));
mSlidingLayout.setDistributedEvenly(true);
mSlidingLayout.setViewPager(mViewPager);
return rootView;
}
@Override
public void onResume() {
super.onResume();
// I TRY TO SET THE TITLE HERE !!
getActivity().getSupportActionBar().setTitle(mainTitle);
}
**适配器:
class PagerAdapter extends FragmentPagerAdapter {
List<Fragment> fragments;
List<String> titles;
...
@Override
public Fragment getItem(int position) {
Fragment fragment = fragments.get(position);
return fragment;
}
@Override
public CharSequence getPageTitle(int position) {
// maybe the problem is in this method.
// this method is supposed to provide the titles for the tab
// but maybe it's also changing the actionbar title
return titles.get(position);
}
我设置的标题每次我输入一个片段时,在onResume
方法中的ActionBar。
谢谢!
编辑1:
我尝试使用新SlidingTabLayout
我已经从谷歌I/O了,结果还是一样!
看来,ActionBar中的标题起初是一个提示,然后当我滑动到另一个片段时,它会变为最后一个加载的片段。
就像是加载片段,每次加载片段时,ActionBar中的标题都会被该片段的标题覆盖。
编辑2:
我改变了我的代码发布的最新版本,它(我使用现在SlidingTabLayout),并显示出我是如何得到我的MAINTITLE。
会发生什么如果您缩短了您的第一个标题? – Fadils
同样的事情,我不认为这是标题长度的问题,因为当我滑动到另一个片段时它显示“Second Title”。 –
你为什么不在活动的onCreate中设置标题? – NasaGeek