简体   繁体   English

片段添加-删除

[英]Fragment adding - removing

I want to add and remove a Fragment through a Button .. Following is the code for the MainActivity. 我想通过一个Button添加和删​​除一个片段。以下是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;}
            }
    });

Use double equals for boolean checks: 对布尔检查使用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;}
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM