Skip to content Skip to sidebar Skip to footer

Get Tag Of Currently Displayed Fragment

I searched to get the currently displayed fragment and found some answers. I tried findFragmentById.It returns null. I'm using FrameLayout in the fragment's xml. Not

Solution 1:

I hope this can help you

At the time of calling fragment set a unique tag to each fragment like

      Fragment fragment=new HomeFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment,"Home").commit();
//home is the tag

In your MainActivity's onBackPressed method check that particular fragment is visible or not

 Fragment hm=getFragmentManager().findFragmentByTag("Home");
     if(hm!=null)
     {
      if(hm.isVisible())
       {
         //exit your application
          MainActivity.this.finish(); 
       }
     }

Post a Comment for "Get Tag Of Currently Displayed Fragment"