【发布时间】:2017-07-27 09:35:36
【问题描述】:
我在一个活动中有三个片段 A、B 和 c,活动有一个带有测试视图标题的工具栏。
现在,当我从一个片段导航到另一个片段时,我想根据显示的片段更改文本视图的文本。
为此,在片段 B 和 C 中,我正在获取主要活动的工具栏和文本视图并更改其标题,如下所示:
final Toolbar toolbar = (Toolbar) ((MainActivity) getActivity()).findViewById(R.id.toolbar);
((MainActivity) getActivity()).setSupportActionBar(toolbar);
TextView title = (TextView) getActivity().findViewById(R.id.textView_Title);
title.setVisibility(View.VISIBLE);
title.setText(R.string.profile);
这很好用。但是当我回到主要片段时,我想再次更改标题但它没有改变。
我尝试在主要活动的 onCreate 方法中设置它,如下所示:
@Override
public void onBackPressed() {
DashboardFragment test = (DashboardFragment) getSupportFragmentManager().findFragmentByTag("DASHBOARD_FRAGMENT");
if (test != null && test.isVisible()) {
//DO STUFF
title = (TextView) findViewById(R.id.textView_Title);
title.setVisibility(View.VISIBLE);
title.setText(R.string.dashboardTitle);
}
else {
//Whatever
}
// Do nothing if the back button is disabled.
if (!mBackPressCancelled) {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStackImmediate();
}
else {
super.onBackPressed();
}
}
}
但是有了这个,它的标题变成了主片段标题,即使 B 片段是可见的。
我该怎么做。请帮忙。谢谢。
编辑:
主片段:
fragmentManager = getSupportFragmentManager();
DashboardFragment fragment1 = new DashboardFragment();
Bundle bundle = new Bundle();
fragment1.setArguments(bundle);
fragmentManager.popBackStack(null,FragmentManager.POP_BACK_STACK_INCLUSIVE);
fragmentManager.beginTransaction().replace(R.id.frame, fragment1, "DASHBOARD_FRAGMENT").commitAllowingStateLoss();
片段:
fragmentManager = ((MainActivity)(mContext)).getSupportFragmentManager();
ProfileFragment fragment1 = new ProfileFragment();
Bundle bundle = new Bundle();
fragment1.setArguments(bundle);
fragmentManager.beginTransaction().add(R.id.frame, fragment1, "PROFILE_FRAGMENT").addToBackStack("B").commit();
B片段
fragmentManager = getActivity().getSupportFragmentManager();
ProfileEditFragment fragment1 = new ProfileEditFragment();
Bundle bundle = new Bundle();
fragment1.setArguments(bundle);
fragmentManager.beginTransaction().add(R.id.frame, fragment1, "PROFILE_EDIT_FRAGMENT").addToBackStack("C").commit();
【问题讨论】:
-
总之,你想根据片段来改变工具栏的标题吗?
标签: java android android-fragments visible fragment-backstack