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


当前回答

有点奇怪,但我看了FragmentManager$FragmentManagerImpl和以下工作为我:

public static Fragment getActiveFragment(Activity activity, int index)
{
    Bundle bundle = new Bundle();
    String key = "i";
    bundle.putInt(key,index);
    Fragment fragment=null;
    try
    {
        fragment = activity.getFragmentManager().getFragment(bundle, key);
    } catch(Exception e){}
    return fragment;
}

要获得第一个活动片段,请使用0作为索引

其他回答

在滚动片段的情况下,当你使用ViewPager类的实例时,假设mVeiwPager,你可以调用mviewpage . getcurrentitem()来获取当前片段int数。

在MainLayout.xml

<?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" android:orientation="vertical" tools:context="unidesign.photo360.MainActivity"> <android.support.design.widget.AppBarLayout android:id="@+id/appbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:fitsSystemWindows="false" android:theme="@style/AppTheme.AppBarOverlay" app:expanded="false"> <android.support.v7.widget.Toolbar android:id="@+id/main_activity_toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" app:popupTheme="@style/AppTheme.PopupOverlay" app:title="@string/app_name"> </android.support.v7.widget.Toolbar> </android.support.design.widget.AppBarLayout> <android.support.v4.view.ViewPager android:id="@+id/view_pager" android:layout_width="match_parent" android:layout_height="wrap_content"> </android.support.v4.view.ViewPager> </android.support.design.widget.CoordinatorLayout>

在MainActivity.kt

class MainActivity : AppCompatActivity() { lateinit var mViewPager: ViewPager lateinit var pageAdapter: PageAdapter // ... override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) pageAdapter = PageAdapter(supportFragmentManager) mViewPager = findViewById(R.id.view_pager) // ... } override fun onResume() { super.onResume() var currentFragment = pageAdapter.getItem(mViewPager.currentItem) // ... }

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

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

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

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

每次当你显示fragment时,你必须把它标签放入backstack:

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_ENTER_MASK);       
ft.add(R.id.primaryLayout, fragment, tag);
ft.addToBackStack(tag);
ft.commit();        

然后当你需要获取当前片段时,你可以使用这个方法:

public BaseFragment getActiveFragment() {
    if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
        return null;
    }
    String tag = getSupportFragmentManager().getBackStackEntryAt(getSupportFragmentManager().getBackStackEntryCount() - 1).getName();
    return (BaseFragment) getSupportFragmentManager().findFragmentByTag(tag);
}

签出此解决方案。我成功拿到了现在的碎片。

if(getSupportFragmentManager().getBackStackEntryCount() > 0){
        android.support.v4.app.Fragment f = 
         getSupportFragmentManager().findFragmentById(R.id.fragment_container);
        if(f instanceof ProfileFragment){
            Log.d(TAG, "Profile Fragment");
        }else if(f instanceof SavedLocationsFragment){
            Log.d(TAG, "SavedLocations Fragment");
        }else if(f instanceof AddLocationFragment){
            Log.d(TAG, "Add Locations Fragment");
        }

如果你在使用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
    }
}