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


当前回答

我最近不得不这么做

public Fragment getCurrentFragment() {
     return fragmentManager.findFragmentById(R.id.container);
}

我终于找到了容器上的最后一个碎片。

其他回答

您可以查询哪个片段被加载到您的Activities内容框架中,并检索片段类,或片段“简单名称”(作为字符串)。

public String getCurrentFragment(){
     return activity.getSupportFragmentManager().findFragmentById(R.id.content_frame).getClass().getSimpleName();
}

用法:

Log.d(TAG, getCurrentFragment());

输出:

D/MainActivity: FragOne

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.

我也坚持这一点。我最后做的,只是声明了一个Fragments数组:

private static PlaceholderFragment[] arrFrg;

(在我的情况下,它是PlaceholderFragment)和包装所有这些片段到这个数组没有标记:)

        public static PlaceholderFragment newInstance(int sectionNumber) {
            final PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            arrFrg[sectionNumber] = fragment;

            return fragment;
}

然后你可以很容易地访问当前显示的片段:

arrFrg[mViewPager.getCurrentItem()];

我知道,这可能不是最好的解决方案,但它对我来说非常适合:)

如果你在使用Kotlin:

var fragment = supportFragmentManager.findFragmentById(R.id.fragment_container)

R.id.fragment_container是片段在其活动中呈现的id

或者如果你想要一个更好的解决方案:

supportFragmentManager.findFragmentById(R.id.content_main)?.let {
    // the fragment exists

    if (it is FooFragment) {
        // The presented fragment is FooFragment type
    }
}

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

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”或使用对您的活动的引用。