案例学习:实现多选兴趣爱好,点击确定后,显示所选兴趣爱好
1.学习准备
2.初始化
public class CheckBoxActivity extends AppCompatActivity {
private CheckBox film,music,sports, others;
private Button confirm;
private TextView tv_hobby;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_box);
film = findViewById(R.id.cb_film);
music = findViewById(R.id.cb_music);
sports = findViewById(R.id.cb_sports);
others = findViewById(R.id.cb_paint);
confirm = findViewById(R.id.bt_confirm);
tv_hobby = findViewById(R.id.tv_hobby);
}
}
3.给确认按钮添加点击事件
public void Confirm(View view) {
List<String> selectedHobby = new ArrayList<>();
if (film.isChecked()) {
selectedHobby.add(film.getText().toString());
}
if (music.isChecked()) {
selectedHobby.add(music.getText().toString());
}
if (sports.isChecked()) {
selectedHobby.add(sports.getText().toString());
}
if (others.isChecked()){
selectedHobby.add(others.getText().toString());
}
if(selectedHobby.isEmpty()){
Toast.makeText(this, "选择不能为空", Toast.LENGTH_SHORT).show();
}else {
tv_hobby.setText("你选择的爱好是"+ selectedHobby.toString());
}
}