I want to add and remove a Fragment through a Button
..
Following is the code for the MainActivity.
When clicking the button for the second time, I get the error message :
java.lang.IllegalStateException: Fragment already added..
Where is my error?
public class MainActivity extends AppCompatActivity {
private Button myBlackButton, myRedButton, myYellowButton;
private TopFragment topFragment;
private YellowFragment yellowFragment;
private RedFragment redFragment;
private boolean status_zwart = true;
private boolean status_geel = true;
private boolean status_rood = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myBlackButton = (Button)findViewById(R.id.zwart_button);
topFragment = new TopFragment();
myBlackButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (status_zwart = true){
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_container, topFragment)
.commit();
status_zwart = false;
}
if (status_zwart = false) {
getSupportFragmentManager()
.beginTransaction()
.remove(topFragment)
.commit();
status_zwart = true;}
}
});