片段添加 - 删除

时间:2018-06-15 12:32:53

标签: java android android-fragments

我想通过Button添加和删除片段。 以下是MainActivity的代码。

第二次点击按钮时,收到错误消息:

java.lang.IllegalStateException: Fragment already added..

我的错误在哪里?

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

2 个答案:

答案 0 :(得分:2)

使用double equals进行布尔检查:

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

答案 1 :(得分:2)

编辑您的代码,如下所示

if (status_zwart) {
    getSupportFragmentManager().beginTransaction()
        .add(R.id.fragment_container, topFragment)
        .commit();
    status_zwart = false;
} else {
    getSupportFragmentManager().beginTransaction().remove(topFragment).commit();
    status_zwart = true;
}