Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 應用開發入門(二十):RadioButton、CheckBox 與 ToggleButton 用法详解

編輯:Android 開發實例

導讀

本文處理三個帶「選中/未選中」雙態的控件:RadioButton 單選、CheckBox 多選、ToggleButton 開關。三者都間接派生自 Button,因此 Button 的通用能力(圖文混排、動態改文案等,可參考作者 Button 專篇)它們照樣具備,這裡只聚焦各自的差異化用法。

共同祖先 CompoundButton

RadioButton、CheckBox、ToggleButton 都繼承自 android.widget.CompoundButton,而 CompoundButton 又繼承自 Button。它在 Button 基礎上封裝了一個 checked 狀態,這正是三者有別於普通按鈕的核心所在,且用法完全一致:

  • android:checked / setChecked(boolean):設定是否選中。
  • isChecked():讀取是否選中。

RadioButton:互斥單選

RadioButton 通常與 RadioGroup 搭配使用。同一個 RadioGroup 內的所有單選鈕互斥,恆有且僅有一個處於選中態;不同 RadioGroup 之間互不干擾,這一點在做多組多選題式的表單時特別有用。

下面的例子用一組單選鈕采集性別,點擊按鈕後把結果彈出提示。

布局代碼:

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" 
  3.     android:layout_width="match_parent" 
  4.     android:layout_height="match_parent" 
  5.     android:orientation="vertical" > 
  6.  
  7.     <TextView 
  8.         android:layout_width="fill_parent" 
  9.         android:layout_height="wrap_content" 
  10.         android:text="Gender:" /> 
  11.     <!-- 定義一個RadioGroup用於包裝RadioButton --> 
  12.     <RadioGroup 
  13.         android:id="@+id/gender" 
  14.         android:layout_width="wrap_content" 
  15.         android:layout_height="wrap_content" > 
  16.  
  17.         <RadioButton 
  18.             android:layout_width="wrap_content" 
  19.             android:layout_height="wrap_content" 
  20.             android:text="male" /> 
  21.  
  22.         <RadioButton 
  23.             android:layout_width="wrap_content" 
  24.             android:layout_height="wrap_content" 
  25.             android:text="female" /> 
  26.     </RadioGroup> 
  27.  
  28.     <Button 
  29.         android:id="@+id/btnGender" 
  30.         android:layout_width="fill_parent" 
  31.         android:layout_height="wrap_content" 
  32.         android:text="選擇性別" /> 
  33.  
  34. </LinearLayout> 

實現代碼:

  1. package com.example.changebutton;  
  2.  
  3. import android.app.Activity;  
  4. import android.os.Bundle;  
  5. import android.view.View;  
  6. import android.widget.Button;  
  7. import android.widget.RadioButton;  
  8. import android.widget.RadioGroup;  
  9. import android.widget.Toast;  
  10.  
  11. public class RadioButtonActivity extends Activity {  
  12.     private RadioGroup group;  
  13.     private Button btnGender;  
  14.  
  15.     @Override 
  16.     protected void onCreate(Bundle savedInstanceState) {  
  17.         // TODO Auto-generated method stub 
  18.         super.onCreate(savedInstanceState);  
  19.         setContentView(R.layout.radiobutton_layout);  
  20.  
  21.         group = (RadioGroup) findViewById(R.id.gender);  
  22.         btnGender = (Button) findViewById(R.id.btnGender);  
  23.         btnGender.setOnClickListener(new View.OnClickListener() {  
  24.             @Override 
  25.             public void onClick(View v) {  
  26.                 // 獲取單選按鈕的選項個數 
  27.                 int len = group.getChildCount();  
  28.                 String msgString = "";  
  29.                 for (int i = 0; i < len; i++) {  
  30.                     //RadioGroup中包含的子View就是一個RadioButton 
  31.                     RadioButton radiobutton = (RadioButton) group.getChildAt(i);  
  32.                     if (radiobutton.isChecked()) {  
  33.                         //如果被選中,則break循環,並且記錄選中信息 
  34.                          msgString = "You choose to be a " 
  35.                              + radiobutton.getText().toString();  
  36.                         break;  
  37.                 }  
  38.               }  
  39.                if (msgString.equals("")) {  
  40.                   Toast.makeText(RadioButtonActivity.this, 
  41.                        "Please select a gender!", Toast.LENGTH_SHORT) 
  42.                     .show();  
  43.                }  
  44.                else {  
  45.                  Toast.makeText(RadioButtonActivity.this, msgString, 
  46.                     Toast.LENGTH_SHORT).show();  
  47.             }  
  48.             }  
  49.         });  
  50.     }  
  51. } 

取值時遍歷 RadioGroup 的子 View 即可,因為互斥關係,最多只有一個 isChecked() 為真,找到後直接跳出循環。實戰中也可以用 getCheckedRadioButtonId() 更直接地拿到 ID。

CheckBox:可多選,可動態生成

CheckBox 與 RadioButton 用法相似,關鍵差異是支持多選,因此不需要外層容器。這個示例順帶演示 Android 動態添加控件的兩種正統做法:

  1. 在布局中給容器控件指定 android:id,Activity 通過 setContentView() 加載後用 findViewById(int) 定位,再逐個 addView 塞進去。
  2. 把單個控件單獨寫成 XML,Activity 用 getLayoutInflater().inflate(int) 動態填充取得實例。

示例用 chooseMethod(boolean) 參數在兩種方式間切換,便於對照。

布局代碼:

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" 
  3.     android:layout_width="match_parent" 
  4.     android:layout_height="match_parent" 
  5.     android:orientation="vertical" 
  6.     android:id="@+id/checkLayout"> 
  7.     <!-- 這裡只是定義了一個按鈕,其他的CheckBox控件在代碼中動態添加 --> 
  8.     <Button 
  9.         android:id="@+id/checkBtn" 
  10.         android:layout_width="fill_parent" 
  11.         android:layout_height="wrap_content" 
  12.         android:text="確定" /> 
  13.  
  14. </LinearLayout> 

若採用動態填充方式,還需一個 CheckBox 的獨立 XML:

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <CheckBox xmlns:android="https://schemas.android.com/apk/res/android" 
  3.     android:layout_width="match_parent" 
  4.     android:layout_height="wrap_content"  > 
  5. </CheckBox> 

實現代碼:

  1. package com.example.changebutton;  
  2.  
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5. import android.app.Activity;  
  6. import android.app.AlertDialog;  
  7. import android.os.Bundle;  
  8. import android.view.View;  
  9. import android.view.View.OnClickListener;  
  10. import android.widget.Button;  
  11. import android.widget.CheckBox;  
  12. import android.widget.LinearLayout;  
  13.  
  14. public class CheckBoxActivity extends Activity implements OnClickListener {  
  15.  
  16.     private List<CheckBox> checkBoxs = new ArrayList<CheckBox>();  
  17.     private Button checkBtn;  
  18.  
  19.     @Override 
  20.     protected void onCreate(Bundle savedInstanceState) {  
  21.         super.onCreate(savedInstanceState);  
  22.         chooseMethod(false);  
  23.         checkBtn = (Button) findViewById(R.id.checkBtn);  
  24.         checkBtn.setOnClickListener(this);  
  25.     }  
  26.  
  27.     @Override 
  28.     public void onClick(View v) {  
  29.         String s = "";  
  30.         //循環cheackBoxs 
  31.         for (CheckBox c : checkBoxs) {  
  32.             if (c.isChecked()) {  
  33.                 //如果選中就添加選中結果到msg中 
  34.                 s += c.getText() + "\n";  
  35.             }  
  36.         }  
  37.         if ("".equals(s)) {  
  38.             s = "您沒有選中選項!";  
  39.         }  
  40.         //使用對話框彈出選中的信息 
  41.         new AlertDialog.Builder(this).setMessage(s) 
  42.                 .setPositiveButton("Exit", null).show();  
  43.     }  
  44.  
  45.     private void chooseMethod(boolean b) {  
  46.         String[] checkboxText = new String[]{"You are student?", 
  47.                 "Do you like Android?","Do you have a girlfriend", 
  48.                 "Do you like online shopping?"};
  49.         if (b) {  
  50.             //使用本文中提到的第一種方式,通過Id動態加載 
  51.             setContentView(R.layout.checkbox_layout);  
  52.             //獲取帶填充的布局控件 
  53.             LinearLayout linearLayout = (LinearLayout) this 
  54.                     .findViewById(R.id.checkLayout);  
  55.             //根據數組,循環添加內容 
  56.             for (int i = 0; i < checkboxText.length; i++) {  
  57.                 CheckBox checkbox = new CheckBox(this);  
  58.                 checkBoxs.add(checkbox);  
  59.                 checkBoxs.get(i).setText(checkboxText[i]);  
  60.                 //把CheckBox加入到布局控件中 
  61.                 linearLayout.addView(checkbox);  
  62.         }  
  63.         }  
  64.         else {  
  65.             //通過動態填充的方式,找到布局文件 
  66.             LinearLayout linearLayout = (LinearLayout) getLayoutInflater() 
  67.                     .inflate(R.layout.checkbox_layout, null);  
  68.             for (int i = 0; i < checkboxText.length; i++) {  
  69.                 //在通過動態填充的方式找到CheckBox的文件 
  70.                 CheckBox checkbox = (CheckBox) getLayoutInflater().inflate( 
  71.                         R.layout.cheackbox, null);  
  72.                 checkBoxs.add(checkbox);  
  73.                 checkBoxs.get(i).setText(checkboxText[i]);  
  74.                 linearLayout.addView(checkbox);  
  75.             }  
  76.             //最後把這個布局文件加載顯示 
  77.             setContentView(linearLayout);  
  78.         }  
  79.     }  
  80. } 

收集結果時把每個 CheckBox 存進 List 統一遍歷,比反覆 findViewById 清爽得多;一個都不選的情況也要記得給用戶提示。

ToggleButton:狀態切換即事件

ToggleButton 是一個帶開關語義的按鈕,兩個狀態各自可配文案:

  • android:textOff / setTextOff(CharSequence):關閉時顯示的文字。
  • android:textOn / setTextOn(CharSequence):打開時顯示的文字。

它提供 setOnCheckedChangeListener(),傳入 OnCheckedChangeListener 接口實現,狀態切換時觸發 onCheckedChange()。這個接口來自 CompoundButton,因此 RadioButton、CheckBox 也能用它做即時響應。

下面的示例用一個 ToggleButton 控制 LinearLayout 在橫向與縱向排列之間切換。

布局代碼:

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" 
  3.     android:layout_width="match_parent" 
  4.     android:layout_height="match_parent" 
  5.     android:orientation="vertical" > 
  6.  
  7.     <ToggleButton 
  8.         android:id="@+id/togBtn" 
  9.         android:layout_width="wrap_content" 
  10.         android:layout_height="wrap_content" 
  11.         android:checked="true" 
  12.         android:textOff="橫向排列" 
  13.         android:textOn="縱向排列" /> 
  14.  
  15.     <LinearLayout 
  16.         android:id="@+id/OriLayout" 
  17.         android:layout_width="match_parent" 
  18.         android:layout_height="match_parent" 
  19.         android:orientation="vertical" > 
  20.  
  21.         <Button 
  22.             android:layout_width="wrap_content" 
  23.             android:layout_height="wrap_content" 
  24.             android:text="btn1" /> 
  25.  
  26.         <Button 
  27.             android:layout_width="wrap_content" 
  28.             android:layout_height="wrap_content" 
  29.             android:text="btn2" /> 
  30.  
  31.         <Button 
  32.             android:layout_width="wrap_content" 
  33.             android:layout_height="wrap_content" 
  34.             android:text="btn3" /> 
  35.     </LinearLayout> 
  36.  
  37. </LinearLayout> 

實現代碼:

  1. package com.example.changebutton;  
  2.  
  3. import android.app.Activity;  
  4. import android.os.Bundle;  
  5. import android.widget.CompoundButton;  
  6. import android.widget.CompoundButton.OnCheckedChangeListener;  
  7. import android.widget.LinearLayout;  
  8. import android.widget.ToggleButton;  
  9.  
  10. public class ToggleButtonActivity extends Activity {  
  11.     private ToggleButton togBtn;  
  12.     private LinearLayout linearLayout;  
  13.  
  14.     @Override 
  15.     protected void onCreate(Bundle savedInstanceState) {  
  16.         // TODO Auto-generated method stub 
  17.         super.onCreate(savedInstanceState);  
  18.         setContentView(R.layout.toggle_layout);  
  19.         togBtn = (ToggleButton) findViewById(R.id.togBtn);  
  20.         linearLayout = (LinearLayout) this.findViewById(R.id.OriLayout);  
  21.  
  22.         togBtn.setOnCheckedChangeListener(new OnCheckedChangeListener() {  
  23.             @Override 
  24.             public void onCheckedChanged(CompoundButton buttonView, 
  25.                     boolean isChecked) {  
  26.                 //通過判斷是否選中,來設置LinearLayout的橫向縱向排列 
  27.                 if (isChecked) {  
  28.                     linearLayout.setOrientation(1);  
  29.                }  
  30.                else {  
  31.                   linearLayout.setOrientation(0);  
  32.                }  
  33.             }  
  34.         });  
  35.     }  
  36. } 

小提示:setOrientation 傳 0 為橫向、1 為縱向,用常量 LinearLayout.HORIZONTAL / VERTICAL 可讀性更好。

小結

三個控件共享 CompoundButton 的 checked 狀態,區別只在選擇語義與專屬屬性。Android 4.0 之後還新增了 Switch 控件,用法與這三者幾乎一致,這裡不再展開。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved