RadioButton and CheckBox, radiobutton
I have been engaged in database development for a long time. Forget it. Because I have been using a small language (PowerBuilder), let's talk about these two most common controls!
RadioButton (single choice) and CheckBox (multiple choice)
RadioButton must be divided by group, instead of CheckBox, so you can play freely;
On the code, familiarize yourself
Code
- PublicclassCheckboxAndRadioBoxActivityextendsAppCompatActivityimplementsCompoundButton. OnCheckedChangeListener,
RadioGroup.OnCheckedChangeListener{
privateRadioGroup rg_sex;
privateCheckBox cb_swimming;
privateCheckBox cb_running;
privateCheckBox cb_study;
privateList<String> hobby =newArrayList<>();
@Override
protectedvoid onCreate(@NullableBundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checkbox_and_radiobox);
rg_sex =(RadioGroup) findViewById(R.id.rg_sex);
cb_swimming =(CheckBox) findViewById(R.id.cb_swimming);
cb_running =(CheckBox) findViewById(R.id.cb_running);
cb_study =(CheckBox) findViewById(R.id.cb_study);
rg_sex.setOnCheckedChangeListener(this);
cb_swimming.setOnCheckedChangeListener(this);
cb_running.setOnCheckedChangeListener(this);
cb_study.setOnCheckedChangeListener(this);
}
@Override
publicvoid onCheckedChanged(CompoundButton buttonView,boolean isChecked){
switch(buttonView.getId()){
case R.id.cb_swimming:
if(isChecked){
Holobby. add ("swimming ");
}else{
Holobby. remove ("swimming ");
}
break;
case R.id.cb_running:
if(isChecked){
Holobby. add ("running ");
}else{
Holobby. remove ("running ");
}
break;
case R.id.cb_study:
if(isChecked){
Holobby. add ("Learning ");
}else{
Holobby. remove ("Learning ");
}
break;
}
String str="";
for(int i =0; i < hobby.size(); i++){
if(i==0){
str = hobby.get(0);
}else{
str +=","+hobby.get(i);
}
}
Toast. makeText (getApplicationContext (), "Hobbies:" + str, Toast. LENGTH_SHORT). show ();
}
@Override
publicvoid onCheckedChanged(RadioGroup group,int checkedId){
switch(checkedId){
case R.id.rb_man:
Toast. makeText (getApplicationContext (), "Gender: male", Toast. LENGTH_SHORT). show ();
break;
case R.id.rb_woman:
Toast. makeText (getApplicationContext (), "Gender: female", Toast. LENGTH_SHORT). show ();
break;
}
}
}
What if the OnCheckedChangeListener of the RadioGroup and CompoundButton conflicts? Their methods are onCheckedChanged. Here I use Activity to implement the above two interfaces at the same time. According to different parameters, RadioGroup and CompoundButton know that they are calling their own interface methods. Although the names are the same, but the parameters are different. here we need to understand two concepts.
From Weizhi note (Wiz)