アプリで (Google ソースから)を使用して、SlidingTabLayout
異なるフラグメント間を移動しています。コンテンツ間をうまくスワイプできますが、私が直面している問題は、奇妙な動作をしているアクション バーのタイトルです。
2 つのタイトル (「First Title」と「Second Title」) を持つ 2 つのタブがあるとします。
| Action bar |
| First Title | Second Title |
を含むフラグメントを最初に入力するSlidingTabLayout
と、アクションバーのタイトルは次のようになります。
| Firs... |
| First Title | Second Title |
スワイプすると (たとえば 2 番目のタブに)、アクションバーのタイトルは次のようになります。
| Second Title |
| First Title | Second Title |
そしてこのまま。少なくとも 1 回スワイプすると、最後に読み込まれた Fragment のタイトルがActionbar に表示されるようです。
私が欲しいのはこれです:
タイトルが何であっても変わらない「メインタイトル」をアクションバーに表示したいと思い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
Fragment を入力するたびに、メソッドで ActionBar のタイトルを設定しています。
ありがとう !
編集1:
SlidingTabLayout
Google I/O から入手した新しいものを使用してみましたが、結果は同じです。
ActionBar のタイトルは最初はヒントのようですが、別のフラグメントにスワイプすると、最後に読み込まれたフラグメントに変わります。
フラグメントをロードしているようで、フラグメントがロードされるたびに、ActionBar のタイトルがそのフラグメントのタイトルで上書きされます。
編集2:
コードを変更して最新バージョンを投稿し (現在は SlidingTabLayout を使用しています)、mainTitle を取得する方法を示しています。