RadioButton與CheckBox,radiobutton
筆者長期從事於資料庫的開發,算了,不提當年了,因為一直用的是小語種(PowerBuilder),還是來說說這兩個最常見的控制項吧!
RadioButton(單選)和CheckBox(多選)
RadioButton必須按組來分,而CheckBox不用,可以自由的玩耍;
上代碼,熟悉下
代碼
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){
hobby.add("遊泳");
}else{
hobby.remove("遊泳");
}
break;
case R.id.cb_running:
if(isChecked){
hobby.add("跑步");
}else{
hobby.remove("跑步");
}
break;
case R.id.cb_study:
if(isChecked){
hobby.add("學習");
}else{
hobby.remove("學習");
}
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(),"愛好:"+ str,Toast.LENGTH_SHORT).show();
}
@Override
publicvoid onCheckedChanged(RadioGroup group,int checkedId){
switch(checkedId){
case R.id.rb_man:
Toast.makeText(getApplicationContext(),"性別:男",Toast.LENGTH_SHORT).show();
break;
case R.id.rb_woman:
Toast.makeText(getApplicationContext(),"性別:女",Toast.LENGTH_SHORT).show();
break;
}
}
}
這裡說說當RadioGroup與CompoundButton的OnCheckedChangeListener出現衝突怎麼辦?他們的方法都是onCheckedChanged,我這裡用Activity同時實現以上兩個介面,根據參數的不同,RadioGroup與CompoundButton他們知道自己去調用自己的介面方法,雖然名稱一樣,但是參數不同呀,這裡就要理解兩個概念了
來自為知筆記(Wiz)