单击复选框时,删除AppCompatActivity中的所有片段?

时间:2016-10-19 13:25:52

标签: android android-fragments

我在片段中有问题,我必须在点击复选框时删除所有添加的片段,但现在片段未被删除,请指导我解决此问题,这里我已经在下面添加了我的代码,

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;


        }
    }


}

1 个答案:

答案 0 :(得分:1)

使用getSupportFragmentManager().beginTransaction().remove(frag1).commit();代替ft.remove(frag1);