Search code examples
javaandroidandroid-layoutdrawerlayout

Checking current opened fragment position while using DrawerLayout


I am using android DrawerLayout from Support Library to show slide menu.I am using a single activity and 5-6 fragments to show them upon selection in DrawerLayout menu.But I have a small problem which is "How do I check which fragment is currently visible so if user selected the menu item which corresponds to already opened fragment. Currently it creating the Fragment again and displaying it which is not good.The function that triggers when clicked on menu item is:

private void selectItem(int position) {

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        // Locate Position
        switch (position) {
        case 0:
            ft.replace(R.id.content_frame, fragment1);
            break;
        case 1:
            ft.replace(R.id.content_frame, fragment2);
            break;
        case 2:
            ft.replace(R.id.content_frame, fragment3);
            break;
        }
        ft.commit();
        mDrawerList.setItemChecked(position, true);
        // Close drawer
        mDrawerLayout.closeDrawer(mDrawerList);
    }

How do I check if the requested fragment is already opened so not to create it again?Is their any method to check this through FragmentManager?


Solution

  • I would add to @Plato's answer. Check get currently displayed fragment question if you haven't already.

    The answer says that when you add the fragment in your transaction, you can use a tag to represent a particular fragment. Something like:

    ft.replace(android.R.id.content, fragment, "MY_FRAGMENT");
    

    Later if you want to check if that fragment is visible, you can do something like:

    RequestedFragment fragment = (RequestedFragment)getFragmentManager().findFragmentByTag("MY_FRAGMENT"); //"My_FRAGMENT" is its tag
    if (fragment.isVisible()) {
       // add your code here 
    }
    

    Hope this helps.