我在一个activity中有三个片段A,B和c,activity有一个带有测试视图标题的工具栏。如何知道任何片段是活动还是可见?
现在,当我从片段导航到片段时,我想根据显示的片段更改文本视图的文本。
对于这个片段中的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();
}
}
}
但是与此改变其到主要片段标题标题甚至乙片段是可见的。
我该怎么做。请帮忙。谢谢。
编辑:
MainFragment:
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();
乙片段
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();
总之,你想要改变工具栏标题根据片段权? –
检查此:https://stackoverflow.com/a/33123356/6021469 –