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


当前回答

它非常简单,不需要编写太多代码 yourFragment.isAdded () 或 yourFragment.isVisible ();

我更喜欢isAdded(),它们都返回布尔值使用它在if条件,必须在onCreate()初始化你的片段,否则你会得到空点异常。

其他回答

public Fragment getVisibleFragment() {
    FragmentManager fragmentManager = getSupportFragmentManager();
    List<Fragment> fragments = fragmentManager.getFragments();
    if(fragments != null) {
        for (Fragment fragment : fragments) {
            if (fragment != null && fragment.isVisible())
                return fragment;
        }
    }
    return null;
}

这对我很有用。在遍历片段列表之前,需要执行空检查。可能存在这样一种情况,即堆栈上没有加载任何片段。

返回的片段可以与您想放入堆栈中的片段进行比较。

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

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

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

为这个FragmentManager返回当前活动的主导航片段。

public @Nullable Fragment getPrimaryNavigationFragment()      
Fragment fragment = fragmentManager.getPrimaryNavigationFragment();  
    

反应式方式:

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

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.