0

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;}
            }
    });
AskNilesh
  • 67,701
  • 16
  • 123
  • 163
Niels Vanwingh
  • 604
  • 1
  • 6
  • 22

2 Answers2

2

Use double equals for boolean checks:

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;}
}
AskNilesh
  • 67,701
  • 16
  • 123
  • 163
Levi Moreira
  • 11,917
  • 4
  • 32
  • 46
2

Edit your code as below

if (status_zwart) {
    getSupportFragmentManager().beginTransaction()
        .add(R.id.fragment_container, topFragment)
        .commit();
    status_zwart = false;
} else {
    getSupportFragmentManager().beginTransaction().remove(topFragment).commit();
    status_zwart = true;
}
AskNilesh
  • 67,701
  • 16
  • 123
  • 163
GianhTran
  • 3,443
  • 2
  • 22
  • 42