离开片段后更新动作条标题 [英] Update ActionBar title after leaving fragment

查看:161
本文介绍了离开片段后更新动作条标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我MainActivity启动我的动作条显示应用程序的标题。一旦您导航通过导航抽屉里的片段,标题改为匹配的片段......然而,一旦您导航回使用后退按钮,标题保持不变,仍然有片段的称号。我期待改回应用程序的标题。

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.

我曾尝试使用了MainActivity.java的onResume()方法,但似乎并没有被调用,一旦你离开一个片段。

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();
    }

有谁知道什么是最好的办法是改变标题回APP_NAME?

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

感谢

推荐答案

事实上摧毁一个活动中的一个片段,并不意味着该活动将调用onResume,首先你要注意到碎片所居住的生活活动范围内,并该片段不改变它的生命周期,只是其中的一部分,你可以做的是片段中得到一个参考的活动,并设置标题回到previous状态,如下图所示:

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");
}

或更多的面向对象的方法是,创建一个声明了一个方法的setTitle previousText接口,需要实现该接口在你的Activity类,并从片段你可以这样做:

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();
            }
    }

这将是接口文件:

public interface SetPreviousTextInterface{
    public void setTitlePreviousText();
}

商祺!

这篇关于离开片段后更新动作条标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆