Android:以编程方式删除特定的复选框

时间:2017-03-11 13:19:41

标签: java android

当我按下按钮时,我想以编程方式将复选框添加到视图中,当复选框被选中时,我希望删除该特定复选框。

    Button btnAdd = (Button) findViewById(R.id.MainActivity_btnAdd);
    final EditText edtHomework = (EditText) findViewById(R.id.MainActivity_edtHomework);
    final LinearLayout llHomework = (LinearLayout) findViewById(R.id.MainActivity_llHomework);

    btnAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            cbHomework = new CheckBox(MainActivity.this);
            cbHomework.setText("• " + edtHomework.getText().toString());
            llHomework.addView(cbHomework);
            edtHomework.setText("");
        }
    });

    cbHomework.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if (cbHomework.isChecked()){
                // remove the checkbox that is ticked
            }
        }
    });

例如,我有一个要完成的事项列表: List of things I must complete

如果勾选(如物理),我希望将其删除。

1 个答案:

答案 0 :(得分:1)

您应该在创建并添加复选框后立即设置OnCheckedChangedListener,如下所示:

btnAdd.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        cbHomework = new CheckBox(MainActivity.this);
        cbHomework.setText(edtHomework.getText().toString());
        llHomework.addView(cbHomework);

        cbHomework.setOnCheckedChangedListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                    if(isChecked)
                        llHomework.removeView(compoundButton);
                }
            });
    }
});