How add and remove fragment with same button

26 Views Asked by At

I am adding a fragment with Button click. I don't want to give a separate button to remove this fragment. So how can i remove this fragment with same button. I tried this

 case R.id.BN_Tab:

                Fragment fragment = new Fragment_Tab();
                Fragment fragment1 = mManager.findFragmentByTag("TAB FRAGMENT");

                if (!fragment.isAdded()) {
                    mManager.beginTransaction()
                            .add(R.id.Tabs_Container, fragment, "TAB FRAGMENT")
                            .commit();
                    Log.d(TAG, "Tab Fragment is Added");

                } else if (fragment1 != null && fragment1.isResumed()) {

                    mManager.beginTransaction()
                            .remove(fragment)
                            .commit();
                    Log.d(TAG, "Tab Fragment is Removed()" );

                }

This method continue adding same fragment and never trigger the else if() block and when i am trying to find Fragment with Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.Tabs_Container); it give NPE.

1

There are 1 best solutions below

1
neo On

Now this simple code works for me

case R.id.BN_Tab:
                Fragment fragment = mManager.findFragmentById(R.id.Tabs_Container);
                if (fragment==null) {
                    mManager.beginTransaction()
                            .add(R.id.Tabs_Container, new Fragment_Tab(), "TAB FRAGMENT")
                            .commit();

                } else  {
                    mManager.beginTransaction()
                            .remove(fragment)
                            .commit();
                }