我想通过按钮添加和删除 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/