使用片段返回堆栈处理 ActionBar 标题? [英] Handling ActionBar title with the fragment back stack?

查看:24
本文介绍了使用片段返回堆栈处理 ActionBar 标题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Activity,我在其中加载了一个 ListFragment,点击后,它会向下钻取一个级别和一个新类型的 ListFragment显示,替换原始的(使用下面的 showFragment 方法).这是放在后堆栈上.

I have an Activity where I load in a ListFragment and, upon clicking, it drills down a level and a new type of ListFragment is shown, replacing the original one (using the showFragment method below). This is placed on the back stack.

一开始,Activity 在操作栏中显示默认标题(即它是根据应用程序的 android:label 自动设置的).

At the beginning, the activity shows the default title in the action bar (i.e. it's set automatically based on the application's android:label).

在显示层次结构中下一级的列表时,单击的项目名称应成为操作栏的标题.

When showing the list for the next level in the hierarchy, the name of the item clicked on should become the action bar's title.

但是,当按返回时,我想恢复原来的默认标题.这不是 FragmentTransaction 知道的,所以标题没有恢复.

However, when pressing Back, I would like the original default title to be restored. This isn't something FragmentTransaction knows about, so the title isn't restored.

我模糊地阅读了 FragmentBreadCrumbs,但这似乎需要使用自定义视图.我正在使用 ActionBarSherlock 并且不想拥有自己的自定义标题视图.

I've vaguely read about FragmentBreadCrumbs, but this seems to require using a custom view. I'm using ActionBarSherlock and would prefer to not have my own custom title view.

这样做的最佳方法是什么?是否有可能没有大量样板代码并且必须跟踪沿途显示的标题?

What is the best way of doing this? Is it possible without a load of boilerplate code and having to keep track of the titles shown along the way?

protected void showFragment(Fragment f) {
  FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
  ft.replace(R.id.fragment_container, f);
  ft.addToBackStack(null);
  ft.commit();
}

推荐答案

在每个片段和每个活动中,我都像这样更改标题.这样,活动标题将始终正确:

In every fragment and every activity I change the title like this. This way the active title will always be correct:

@Override
public void onResume() {
    super.onResume();
    // Set title
    getActivity().getActionBar()
        .setTitle(R.string.thetitle);
}

在某些情况下,不会在片段内部调用 onResume.在其中一些情况下,我们可以使用:

There is some cases where onResume isn't called inside fragments. In some of these cases we can use:

public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if(isVisibleToUser) {
        // Set title
        getActivity().getActionBar()
            .setTitle(R.string.thetitle);
    }
}

这篇关于使用片段返回堆栈处理 ActionBar 标题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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