How to add / remove a fragment on a button?

I currently have a RELATIVE_LAYOUT container, which I use to add my fragment. I use the OnClickListener on the button to load the XML fragment of the fragment into the RelativeLayout container.

I want to ensure that when I click the button once, the fragment should load ... and when I click it again, the fragment must be deleted. I already tried to use an integer to determine if the fragment was 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(); } }); } 
+6
source share
1 answer

Your problem is that you create a new Fragment every time you click Button . You need to get a link to the currently added Fragment , and then delete it.

In addition, you no longer need to use the flag. When adding a Fragment you can mark . After removing the Fragment you can use the tag used to add the Fragment to get a link to the currently added Fragment .

Here is an example of how you should do this:

 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 ... } 
+12
source

Source: https://habr.com/ru/post/971614/


All Articles