Maverick.pe Maverick.pe - 22 days ago 6
Android Question

ActionBar Title dynamically change with fragment

I have 1 Activity with 3 Fragments inside (Home-Login-RestorePass) Initially, HomeFragment shows and the other two are hidden. I want that the ActionBar Title change depending on which Fragment is showing.

I'm trying in my Activity with:

public void setActionBarTitle(String title){
getSupportActionBar().setTitle(title);
}

@Override
public void onResume() {
super.onResume();
// Set title
setActionBarTitle(getString(R.string.app_name));
}


and the fragments has the same:

@Override
public void onResume() {
super.onResume();
// Set title
((LoginActivity) getActivity()).setActionBarTitle(getString(R.string.fragment_login));
}


But it doesn't work. It always show R.string.fragment_login on the title.

I'm using FragmentTransaction for the fragment transition:

btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
HomeFragment homeFragment = (HomeFragment) getFragmentManager().findFragmentById(R.id.fragmentHome);
LoginFragment loginFragment = (LoginFragment) getFragmentManager().findFragmentById(R.id.fragmentLogin);
ft.hide(homeFragment).addToBackStack(null);
ft.show(loginFragment).addToBackStack(null).commit();
}
});


Additionally if i could make appear an Arrow Button (Back) on ActionBar depending of the fragment would be great.

Thanks for your time! Regards.

Answer

Use this method in activity to change the Fragment and set the title programmatically:

private void displayFragment(int position) {
    // update the main content by replacing fragments
    Fragment fragment = null;
    String title = "";
    switch (position) {
    case 0:
        fragment = new Home();
        title = "Home";
        break;
    case 1:
        fragment = new Login();
        title = "Login";
        break;
    case 2:
        fragment = new RestorePass();
        title = "Restore Password";
        break;

    default:
        break;
    }

    // update selected fragment and title
    if (fragment != null) {
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.frame_container, fragment).commit();
        getSupportActionBar().setTitle(title);
        // change icon to arrow drawable
        getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_arrow);
    }
}

For example, you want Fragment Home to be displayed:

displayFragment(0);