我在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文件中,如何获得当前显示的片段实例?


当前回答

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.

其他回答

我的方法是基于try / catch,如下所示:

MyFragment viewer = null;
    if(getFragmentManager().findFragmentByTag(MY_TAG_FRAGMENT) instanceOf MyFragment){
    viewer = (MyFragment) getFragmentManager().findFragmentByTag(MY_TAG_FRAGMENT);
}

但也许有更好的办法……

反应式方式:

Observable.from(getSupportFragmentManager().getFragments())
    .filter(fragment -> fragment.isVisible())
    .subscribe(fragment1 -> {
        // Do something with it
    }, throwable1 -> {
        // 
    });

如果您正在使用Jetpack导航库:

val currentFragment = defaultNavigator.currentDestination

有点晚了,但有兴趣的人 如果你知道你想要的片段在FragmentManager中的索引,只需获得它的引用并检查isMenuVisible()函数!在这里:

getSupportFragmentManager().getFragments().get(0).isMenuVisible()

如果为真,它对用户可见,等等!

在SupportFragmentManager中有一个叫做findFragmentById()的方法。我在活动容器中使用它,就像:

public Fragment currentFragment(){
    return getSupportFragmentManager().findFragmentById(R.id.activity_newsfeed_frame);
}

这就是如何获得当前的碎片。如果你有自定义片段,需要检查它是什么片段,我通常使用instanceof:

if (currentFragment() instanceof MyFrag){
    // Do something here
}