gpt4 book ai didi

android - 单击复选框时删除 AppCompatActivity 中的所有 fragment ?

转载 作者:行者123 更新时间:2023-11-30 00:56:09 26 4
gpt4 key购买 nike

我的 fragment 有问题,我必须在单击复选框时删除所有添加的 fragment ,但现在 fragment 没有被删除,请指导我解决这个问题,我在下面添加了我的代码,

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
TextView txtVw_showfirstfragment,txtVw_showsecondfragment;
FragmentTransaction ft;
CheckBox checkBox;
fragment1 frag1 = new fragment1();
fragment2 frag2 = new fragment2();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtVw_showfirstfragment = (TextView) findViewById(R.id.txtVw_showfirstfragment);
txtVw_showsecondfragment = (TextView) findViewById(R.id.txtVw_showsecondfragment);
checkBox = (CheckBox)findViewById(R.id.checkBox);
txtVw_showfirstfragment.setOnClickListener(this);
txtVw_showsecondfragment.setOnClickListener(this);
checkBox.setText("I Agree"); // Prompting "Hide Password"
// Begin the transaction
checkBox.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
if (isChecked) {
if(frag1!=null) ft.remove(frag1);
if(frag2!=null) ft.remove(frag2);
}
}
} );


}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.txtVw_showfirstfragment:
String backFragment1 = getApplicationContext().getClass().getName();
ft = getSupportFragmentManager().beginTransaction();

// Replace the contents of the container with the new fragment
ft.replace(R.id.your_placeholder,frag1);
ft.addToBackStack(backFragment1);

// Complete the changes added above
ft.commit();
break;
case R.id.txtVw_showsecondfragment:
String backFragment2 = getApplicationContext().getClass().getName();
ft = getSupportFragmentManager().beginTransaction();

// Replace the contents of the container with the new fragment
ft.replace(R.id.your_placeholder,frag2);
ft.addToBackStack(backFragment2);

// Complete the changes added above
ft.commit();
break;


}
}


}

最佳答案

使用 getSupportFragmentManager().beginTransaction().remove(frag1).commit(); 而不是 ft.remove(frag1);

关于android - 单击复选框时删除 AppCompatActivity 中的所有 fragment ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40132746/

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