简体   繁体   中英

Update ActionBar title after leaving fragment

When my MainActivity is launched my ActionBar shows the app title. Once you navigate to a fragment through the nav drawer, the title is changed to match the fragment... however, once you navigate back using the back button, the title is left untouched and still has the title of the fragment. I am looking to change it back to the application Title.

I have tried to use the onResume() method in the MainActivity.java but it appears that does not get called once you leave a fragment.

@Override
    public void onResume() {
        super.onResume();
        // Set title
        getActionBar().setTitle("FuelR");
        invalidateOptionsMenu();
    }

Does anyone know what the best way would be to change the title back to the app_name ?

Thanks

Indeed destroying a Fragment within an Activity doesn't mean the activity will call onResume, first you have to notice that the Fragment lives within the Activity life context, and the Fragment do not alter it's life cycle, is just part of it, what you could do is within the fragment get a reference to the activity and set the title back to previous state, as shown below:

//In Fragment
@Override
public void onDestroyView() {
    super.onDestroyView();
    ((Cast If Necessary)getActivity()).getActionBar().setTitle("Previous Title");
}

Or a more OOP approach would be, creating an interface that declares a method setTitlePreviousText, you implement that interface in your Activity class and from the fragment you could do this:

    //In Fragment
    @Override
    public void onDestroyView() {
        super.onDestroyView();
            Activity act = getActivity()
            if(act instanceof SetPreviousTextInterface){
                //setTitlePreviousText will be called giving you the chance to just change it back...
            ((SetPreviousTextInterface)act).setTitlePreviousText();
            }
    }

This would be the interface file:

public interface SetPreviousTextInterface{
    public void setTitlePreviousText();
}

Regards!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM