1 回答
TA贡献1786条经验 获得超11个赞
您需要将侦听器附加到复选框并将该模式检查移至方法内部onCheckedChanged()。通过这种方式,您的复选框可以通知活动并重新计算 的值pattern:
public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
CheckBox cb1, cb2, cb3, cb4;
ImageView img;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cb1 = findViewById(R.id.persona);
cb2 = findViewById(R.id.car);
cb3 = findViewById(R.id.calle);
cb4 = findViewById(R.id.music);
img = findViewById(R.id.imagen);
cb1.setOnCheckedChangeListener(this);
cb2.setOnCheckedChangeListener(this);
cb3.setOnCheckedChangeListener(this);
cb4.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
int pattern = (cb1.isChecked() ? 0b0001 : 0)
| (cb2.isChecked() ? 0b0010 : 0)
| (cb3.isChecked() ? 0b0100 : 0)
| (cb4.isChecked() ? 0b1000 : 0);
switch (pattern) {
// No selection
case 0b0000:
img.setImageResource(R.drawable.def);
break;
//Person
case 0b0001:
img.setImageResource(R.drawable.wick);
break;
//Car
case 0b0010:
img.setImageResource(R.drawable.car);
break;
}
}
}
添加回答
举报