在我的解决方案中,我必须为工具栏和折叠工具栏设置标题才能使其正常工作。
所以在 OnCreate 中:
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
collapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
然后当我切换片段时,我在选择选项卡时为两者设置标题:
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//TAB1 - THE DEFAULT TAB
switch (item.getItemId()) {
case R.id.tab_rooms:
toolbar.setTitle("My Title");
collapsingToolbar.setTitle("My Title");
fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
fragment = new RoomsFragment();
transaction.replace(R.id.fragment_container, fragment);
transaction.addToBackStack(null);
transaction.commit();
return true;
case R.id.tab_shisha:
toolbar.setTitle("My Title2");
collapsingToolbar.setTitle("My Title2");
fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
fragment = new ShishaFragment();
transaction.replace(R.id.fragment_container, fragment);
transaction.addToBackStack(null);
transaction.commit();
return true;
}
return false;
}