Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> RadioButton與CheckBox,radiobutton

RadioButton與CheckBox,radiobutton

編輯:關於android開發

RadioButton與CheckBox,radiobutton


筆者長期從事於數據庫的開發,算了,不提當年了,因為一直用的是小語種(PowerBuilder),還是來說說這兩個最常見的控件吧!

RadioButton(單選)和CheckBox(多選)
  • RadioButton必須按組來分,而CheckBox不用,可以自由的玩耍;
  •  
  • 上代碼,熟悉下
  •  
  • 代碼
    1. publicclassCheckboxAndRadioBoxActivityextendsAppCompatActivityimplementsCompoundButton.OnCheckedChangeListener,
    2. RadioGroup.OnCheckedChangeListener{
    3. privateRadioGroup rg_sex;
    4. privateCheckBox cb_swimming;
    5. privateCheckBox cb_running;
    6. privateCheckBox cb_study;
    7. privateList<String> hobby =newArrayList<>();
    8. @Override
    9. protectedvoid onCreate(@NullableBundle savedInstanceState){
    10. super.onCreate(savedInstanceState);
    11. setContentView(R.layout.activity_checkbox_and_radiobox);
    12. rg_sex =(RadioGroup) findViewById(R.id.rg_sex);
    13. cb_swimming =(CheckBox) findViewById(R.id.cb_swimming);
    14. cb_running =(CheckBox) findViewById(R.id.cb_running);
    15. cb_study =(CheckBox) findViewById(R.id.cb_study);
    16. rg_sex.setOnCheckedChangeListener(this);
    17. cb_swimming.setOnCheckedChangeListener(this);
    18. cb_running.setOnCheckedChangeListener(this);
    19. cb_study.setOnCheckedChangeListener(this);
    20. }
    21. @Override
    22. publicvoid onCheckedChanged(CompoundButton buttonView,boolean isChecked){
    23. switch(buttonView.getId()){
    24. case R.id.cb_swimming:
    25. if(isChecked){
    26. hobby.add("游泳");
    27. }else{
    28. hobby.remove("游泳");
    29. }
    30. break;
    31. case R.id.cb_running:
    32. if(isChecked){
    33. hobby.add("跑步");
    34. }else{
    35. hobby.remove("跑步");
    36. }
    37. break;
    38. case R.id.cb_study:
    39. if(isChecked){
    40. hobby.add("學習");
    41. }else{
    42. hobby.remove("學習");
    43. }
    44. break;
    45. }
    46. String str="";
    47. for(int i =0; i < hobby.size(); i++){
    48. if(i==0){
    49. str = hobby.get(0);
    50. }else{
    51. str +=","+hobby.get(i);
    52. }
    53. }
    54. Toast.makeText(getApplicationContext(),"愛好:"+ str,Toast.LENGTH_SHORT).show();
    55. }
    56. @Override
    57. publicvoid onCheckedChanged(RadioGroup group,int checkedId){
    58. switch(checkedId){
    59. case R.id.rb_man:
    60. Toast.makeText(getApplicationContext(),"性別:男",Toast.LENGTH_SHORT).show();
    61. break;
    62. case R.id.rb_woman:
    63. Toast.makeText(getApplicationContext(),"性別:女",Toast.LENGTH_SHORT).show();
    64. break;
    65. }
    66. }
    67. }
     
  • 這裡說說當RadioGroup與CompoundButton的OnCheckedChangeListener出現沖突怎麼辦?他們的方法都是onCheckedChanged,我這裡用Activity同時實現以上兩個接口,根據參數的不同,RadioGroup與CompoundButton他們知道自己去調用自己的接口方法,雖然名稱一樣,但是參數不同呀,這裡就要理解兩個概念了


  • 來自為知筆記(Wiz)



    1. 上一頁:
    2. 下一頁:
    熱門文章
    閱讀排行版
    Copyright © Android教程網 All Rights Reserved