Hi, everyone. I'd like to change the title of the toolbar according to the fragment in the navigation. Main (Fragment) also listed the same menu as Navigation. When the button is pressed in the Main (Fragment), it is successful to become a setTitle in the fragment It was also successful to become a setTitle when other menus were selected in the navigation. However, if you enter the Main-Fragment menu in the navigation and press another menu, the setTitle does not work. We tried in many ways, but all failed. How can I setTitle?
MainActivity.java
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// // Handle navigation view item clicks here.
int id = item.getItemId();
Fragment fragment = null;
String title = getString(R.string.app_name);
if (id == R.id.nav_home) {
fragment = new Main();
title = "";
} } else if (id == R.id.nav_order) {
fragment = new OrderManage();
title = "Manage orders";
}
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_fragment_layout, fragment);
ft.commit();
}
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle(title);
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
//Move to another fragment.
public void replaceFragment(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_fragment_layout, fragment).commit();
}
Order Management Fragment
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_order_manage, container, false);
getActivity().setTitle ("Order Management");
MainFragment
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.orderManageCV:
((MainActivity) getActivity()).replaceFragment(OrderManage.newInstance());
break;
}
}
The current fragment seems to be managed by MainActivity. You can create a method to handle the action bar in MainActivity, and modify the title whenever the fragment is onResume
or at the appropriate life cycle. Have you tried this way?
MainActivity
public void setActionBarTitle(String title) {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(title);
}
}
Something Fragment
@Override
public void onResume() {
super.onResume();
FragmentActivity activity = getActivity();
if (activity != null) {
((MainActivity) activity).setActionBarTitle ("Title");
}
}
© 2024 OneMinuteCode. All rights reserved.