gpt4 book ai didi

java - fragment 添加-删除

转载 作者:行者123 更新时间:2023-12-01 17:50:24 26 4
gpt4 key购买 nike

我想通过按钮添加和删除 fragment ..以下是 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;}
}
});

最佳答案

使用双等号进行 boolean 检查:

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 - fragment 添加-删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50875718/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com