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

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

问题描述

我使用的是兼容包使用的片段与Android 2.2。 当使用的片段,并将它们添加之间转变到backstack,我想坡平出来的后达到onResume一个活动,即,每当一片段被带到前台(对用户可​​见)的相同的行为backstack,我想某种回调将片段(执行上的共享资源的用户界面一定的变化,例如)。

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实现:

getListener implementation:

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()会后,后退是pressed调用。一些警告,虽然:

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

  1. 它假定你添加的所有 交易的backstack(使用 FragmentTransaction.addToBackStack())
  2. 这将是每个堆栈时激活 改变(你可以存储其他东西在 背面堆栈如动画),以便 你可能会多次调用了 片段的同一个实例。
  1. It assumes you added all transactions to the backstack (using FragmentTransaction.addToBackStack())
  2. It will be activated upon each stack change (you can store other stuff in the back stack such as animation) so you might get multiple calls for the same instance of fragment.

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

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