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;}
Abhi9 source share