【问题标题】:Fragment adding - removing片段添加 - 删除
【发布时间】:2018-06-15 12:32:52
【问题描述】:

我想通过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;}
            }
    });

【问题讨论】:

标签: java android android-fragments


【解决方案1】:

使用双等号进行布尔检查:

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

【讨论】:

  • 更好if (status_zwart){// logic}else{// logic}
【解决方案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;
}

【讨论】:

    猜你喜欢
    • 2020-08-07
    • 2013-12-03
    • 2014-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-07
    • 1970-01-01
    相关资源
    最近更新 更多