Update ActionBar title after leaving fragment

牧云@^-^@ 提交于 2019-12-10 11:19:19

问题


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


回答1:


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!



来源:https://stackoverflow.com/questions/22178322/update-actionbar-title-after-leaving-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!