当我按下按钮时,我想以编程方式将复选框添加到视图中,当复选框被选中时,我希望删除该特定复选框。
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
}
}
});
如果勾选(如物理),我希望将其删除。
答案 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);
}
});
}
});