我在Android中玩碎片。

我知道我可以通过使用以下代码更改一个片段:

FragmentManager fragMgr = getSupportFragmentManager();
FragmentTransaction fragTrans = fragMgr.beginTransaction();

MyFragment myFragment = new MyFragment(); //my custom fragment

fragTrans.replace(android.R.id.content, myFragment);
fragTrans.addToBackStack(null);
fragTrans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
fragTrans.commit();

我的问题是,在Java文件中,如何获得当前显示的片段实例?


当前回答

在这些情况下,使用事件总线(如Otto、EventBus或RxJava总线)特别方便。

虽然这种方法不一定会将当前可见的片段作为对象传递给您(尽管也可以这样做,但这会导致更长的调用链),但它允许您在当前可见的片段上执行操作(这通常是您想要知道当前可见的片段所做的事情)。

确保您尊重片段生命周期,并在适当的时间注册/取消注册事件总线 此时,您需要知道当前可见的片段并执行一组操作。使用事件总线输出事件。

所有已注册到总线的可见片段都将执行必要的操作。

其他回答

In the main activity, the onAttachFragment(Fragment fragment) method is called when a new fragment is attached to the activity. In this method, you can get the instance of the current fragment. However, the onAttachFragment(Fragment fragment) method is not called when a fragment is popped off the back stack, ie, when the back button is pressed to get the top fragment on top of the stack. I am still looking for a callback method that is triggered in the main activity when a fragment becomes visible inside the activity.

我遇到了一个类似的问题,我想知道当返回键被按下时最后显示的片段是什么。我用了一个非常简单的方法。每次我打开一个片段,在onCreate()方法中,我在我的单例中设置了一个变量(用你的片段的名称替换“myFragment”)

MySingleton.currentFragment = myFragment.class;

变量在单例中声明为

public static Class currentFragment = null; 

然后在onBackPressed()中检查

    if (MySingleton.currentFragment == myFragment.class){
        // do something
        return;
    }
    super.onBackPressed();

确保调用super.onBackPressed();在“返回”之后,否则应用程序将处理返回键,这在我的情况下导致应用程序终止。

如果你从父活动中获得Fragment的当前实例,你可以

findFragmentByID(R.id.container);

这实际上是视图中填充的fragment的当前实例。我也有同样的问题。我不得不加载相同的片段两次,保持一个备份。

下面的方法不起作用。它只是得到一个带有标签的片段。不要在这个方法上浪费时间。我相信它有它的用途,但获得同一片段的最新版本不是其中之一。

findFragmentByTag()

如果您使用支持库v13,则此问题已修复,您应该简单地覆盖:

@Override
public void setUserVisibleHint(boolean isVisibleToUser)
{
    // TODO Auto-generated method stub
    super.setUserVisibleHint(isVisibleToUser);
}

问题是,你不能将两者混合,因为fragment与版本4的fragment类不兼容。

如果不是,并且您正在使用V4支持库,则将setPrimaryItem方法覆盖到FragmentStatePagerAdapter。

我用这个在大列表中更新Actionbat标题。

受泰尼回答的启发,以下是我的观点。与大多数其他实现相比几乎没有修改。

private Fragment getCurrentFragment() {
    FragmentManager fragmentManager = myActivity.getSupportFragmentManager();
    int stackCount = fragmentManager.getBackStackEntryCount();
    if( fragmentManager.getFragments() != null ) return fragmentManager.getFragments().get( stackCount > 0 ? stackCount-1 : stackCount );
    else return null;
}

如果“myActivity”是您当前的活动,则将“myActivity”替换为“this”或使用对您的活动的引用。