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();
}
});
}