简体   繁体   English

离开片段后更新ActionBar标题

[英]Update ActionBar title after leaving fragment

When my MainActivity is launched my ActionBar shows the app title. 启动MainActivity时,ActionBar会显示应用程序标题。 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. 我试图在MainActivity.java中使用onResume()方法,但是一旦您留下一个片段,它似乎就不会被调用。

@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 ? 有谁知道将标题改回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: 确实,销毁一个Activity中的一个片段并不意味着该活动将调用onResume,首先您必须注意到Fragment处于Activity生命上下文中,并且Fragment不会改变其生命周期,只是它的一部分,您可以在片段中获取对活动的引用,并将标题设置回先前的状态,如下所示:

//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: 或更进一步的OOP方法是,创建一个声明方法setTitlePreviousText的接口,然后在Activity类中实现该接口,然后从片段中执行以下操作:

    //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! 问候!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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