从后堆栈恢复的片段 [英] Fragments onResume from back stack

查看:25
本文介绍了从后堆栈恢复的片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用兼容包在 Android 2.2 中使用 Fragments.当使用片段并将它们之间的转换添加到后台堆栈时,我想实现与活动的 onResume 相同的行为,即,每当一个片段在弹出后被带到前台"(对用户可见)时backstack,我希望在片段中激活某种回调(例如,对共享 UI 资源执行某些更改).

I'm using the compatibility package to use Fragments with Android 2.2. When using fragments, and adding transitions between them to the backstack, I'd like to achieve the same behavior of onResume of an activity, i.e., whenever a fragment is brought to "foreground" (visible to the user) after poping out of the backstack, I'd like some kind of callback to be activated within the fragment (to perform certain changes on a shared UI resource, for instance).

我看到片段框架中没有内置回调.有什么好的做法可以实现这一目标吗?

I saw that there is no built in callback within the fragment framework. is there s a good practice in order to achieve this?

推荐答案

由于缺乏更好的解决方案,我得到了这个解决方案:假设我有 1 个活动 (MyActivity) 和几个相互替换的片段(一次只有一个可见).

For a lack of a better solution, I got this working for me: Assume I have 1 activity (MyActivity) and few fragments that replaces each other (only one is visible at a time).

在 MyActivity 中,添加这个监听器:

In MyActivity, add this listener:

getSupportFragmentManager().addOnBackStackChangedListener(getListener());

(如您所见,我正在使用兼容包).

(As you can see I'm using the compatibility package).

getListener 实现:

private OnBackStackChangedListener getListener()
    {
        OnBackStackChangedListener result = new OnBackStackChangedListener()
        {
            public void onBackStackChanged() 
            {                   
                FragmentManager manager = getSupportFragmentManager();

                if (manager != null)
                {
                    MyFragment currFrag = (MyFragment) manager.findFragmentById(R.id.fragmentItem);

                    currFrag.onFragmentResume();
                }                   
            }
        };

        return result;
    }

MyFragment.onFragmentResume() 将在按下返回"后调用.一些警告:

MyFragment.onFragmentResume() will be called after a "Back" is pressed. few caveats though:

  1. 假设您添加了所有到后台堆栈的交易(使用FragmentTransaction.addToBackStack())
  2. 它会在每个堆栈上激活更改(您可以将其他东西存储在返回堆栈如动画)所以你可能会接到多个电话相同的片段实例.

这篇关于从后堆栈恢复的片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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