How to add/remove Fragment on Button click?
Asked Answered
M

1

7

At present I have got a "RELATIVE_LAYOUT" container which I am using for adding my fragment. I am using OnClickListener on a button to load the fragment XML layout into the RelativeLayout container.

What I want to achieve is that when I press the button once, the fragment should load...and when I press it again the fragment should be removed. I've already tried using integer to identify if fragment is loaded, but failed. Any help Appreciated...

CODE:

public class MainActivity extends Activity {
    Button B1,B2;
    int boolb1=0, boolb2=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        B1 = (Button)findViewById(R.id.btn1);
        B2 = (Button)findViewById(R.id.btn2);

        B1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                FragmentManager fm = getFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
                FragmentOne f1 = new FragmentOne();

                if(boolb1==0)
                {ft.add(R.id.frg1, f1);
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                boolb1=1;}
                else
                {ft.remove(f1);
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
                boolb1=0;}
                //ft.addToBackStack("f1");
                ft.commit();
            }
        });

        B2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                FragmentManager fm = getFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
                FragmentTwo f2 = new FragmentTwo();

                if(boolb2==0) {
                   ft.add(R.id.frg2, f2);
                   ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                   boolb2=1;
                } else {
                   ft.remove(f2);
                   ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
                   boolb2=0;
                }

                //ft.addToBackStack("f2");
                ft.commit();
            }
        });
    }
Manteltree answered 1/7, 2014 at 19:1 Comment(0)
A
14

Your issue is that you create a new Fragment everytime you click the Button. You need to get a reference to the currently added Fragment and then remove that one.

Furthermore, you no longer need to use the flag. When adding the Fragment, you can tag it. Upon removing the Fragment, you can use the tag used for adding the Fragment to get a reference to the currently added Fragment.

Here is an example of how you should do it:

private Button B1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    B1 = (Button)findViewById(R.id.btn1);

    B1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            FragmentManager fm = getFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            FragmentOne f = (FragmentOne) fm.findFragmentByTag("tag");

            if(f == null) {  // not added
                f = new FragmentOne();
                ft.add(R.id.frg1, f, "tag");
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

            } else {  // already added

                ft.remove(f);
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
            }

            ft.commit();
        }
    });

    // and so on ...
}
Abstractionist answered 1/7, 2014 at 19:11 Comment(4)
Yes, I would just add that better approach is to completely remove "added" variable and just decide by presention of fragments in fragment manager.. in that case you will have less work with restoring state after rotation of screenPivoting
Excellent answer...one doubt though, when the first time I press the button, java creates an object of FragmentOne f1 and passes it the value returned by findFragmentByTag, but the tag "tag" is not associated yet with any fragment since we do that in the if block. So, shouldn't that generate an error???Manteltree
No, that shouldnt generate an error, FragmentOne f will be null and branch if(f == null) will be executed ..Pivoting
Okay... So the value initially stored in f1 will be null since tag is not associated with any fragment... RightManteltree

© 2022 - 2024 — McMap. All rights reserved.