Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't remove a fragment from FrameLayout?

I have a layout for landscape mode that shows a ListView on the left and a FrameLayout on the right. When an item is selected from the list another fragment is added to the FrameLayout

MyFragment myFragment = (MyFragment) fragmentManager.findFragmentById(R.id.myFrameLayout);
FragmentTransaction ft = fragmentManager.beginTransaction();
if (myFragment == null) {
    myFragment = new MyFragment(uri);
    ft.replace(R.id.myFrameLayout, playerFragment);
    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    ft.commitAllowingStateLoss();
}

Later on I press delete in the list view and remove the last item in the list, and I try to remove the fragment so that nothing is shown, but it doesn't work, my fragment remains on the screen. The code for removing is:

MyFragment myFragment = (MyFragment) fragmentManager.findFragmentById(R.id.myFrameLayout);
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.remove(myFragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
ft.commitAllowingStateLoss();

Any ideas why it is not being removed from the View?

like image 205
DaveJohnston Avatar asked Mar 28 '12 16:03

DaveJohnston


2 Answers

@DaveJohnston I have tried your code for remove fragment I just molded....thanks :)

Hey I dont know this is solution to your problem or not but you try this way it will work:

Approach to add fragment:

YourFragment yourFrament;

//Add your Fragment
public void addYourFragment(){
yourFragment = new YourFragment();

FragmentTransaction transation = getSupportFragmentManager().beginTransaction();
transation.replace(R.id.yourFlowLayout, yourFragment);

        transation.commit();

}   

Approach to remove Fragment:

 //Remove Fragment
    public void removeYourFragment(){
     FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            if (yourFragment != null) {           
                transaction.remove(yourFragment);
                transaction.commit();
                transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
                yourFragment = null;
            }
    }
like image 67
Gru Avatar answered Nov 15 '22 15:11

Gru


are you declaring the fragment in xml? Citing Dianne Hackborn from google:

Defining fragments in XML is mostly intended for things that are going to stay around. If you are going to add and remove, you should probably consistently do it dynamically.

hope it helps

like image 30
Blackbelt Avatar answered Nov 15 '22 15:11

Blackbelt