我在我的應用中使用了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