How do I get the currently displayed fragment?

前端 未结 30 1736
青春惊慌失措
青春惊慌失措 2020-11-22 11:21

I am playing with fragments in Android.

I know I can change a fragment by using the following code:

FragmentManager fragMgr = getSupportFragmentManag         


        
相关标签:
30条回答
  • 2020-11-22 11:47

    You can query which fragment is loaded into your Activities content frame, and retrieve the fragment class, or fragment 'simple name' (as a string).

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

    Usage:

    Log.d(TAG, getCurrentFragment());
    

    Outputs:

    D/MainActivity: FragOne
    
    0 讨论(0)
  • 2020-11-22 11:48

    Sev's answer works for when you hit the back button or otherwise change the backstack.

    I did something slightly different, though. I have a backstack change listener setup on a base Fragment and its derived fragments and this code is in the listener:

    Fragment f = getActivity().getSupportFragmentManager().findFragmentById(R.id.container);
    
    if (f.getClass().equals(getClass())) {
        // On back button, or popBackStack(),
        // the fragment that's becoming visible executes here,
        // but not the one being popped, or others on the back stack
    
        // So, for my case, I can change action bar bg color per fragment
    }
    
    0 讨论(0)
  • 2020-11-22 11:49

    In case of scrolled fragments, when your use instance of ViewPager class, suppose mVeiwPager, you can call mViewPager.getCurrentItem() for get current fragment int number.

    in 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>

    in 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)
    //         ...
              }

    0 讨论(0)
  • 2020-11-22 11:50

    My method is based on try / catch like this :

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

    But there may be a better way ...

    0 讨论(0)
  • 2020-11-22 11:50

    If you are using the AndroidX Navigation:

    val currentFragment = findNavController(R.id.your_navhost).?currentDestination
    

    For more info on this navigation component: https://developer.android.com/guide/navigation/navigation-getting-started

    0 讨论(0)
  • 2020-11-22 11:50

    1)

    ft.replace(R.id.content_frame, fragment, **tag**).commit();
    

    2)

    FragmentManager fragmentManager = getSupportFragmentManager();
    Fragment currentFragment = fragmentManager.findFragmentById(R.id.content_frame);
    

    3)

    if (currentFragment.getTag().equals(**"Fragment_Main"**))
    {
     //Do something
    }
    else
    if (currentFragment.getTag().equals(**"Fragment_DM"**))
    {
    //Do something
    }
    
    0 讨论(0)
提交回复
热议问题