編輯:Android 開發實例
本文處理三個帶「選中/未選中」雙態的控件:RadioButton 單選、CheckBox 多選、ToggleButton 開關。三者都間接派生自 Button,因此 Button 的通用能力(圖文混排、動態改文案等,可參考作者 Button 專篇)它們照樣具備,這裡只聚焦各自的差異化用法。
RadioButton、CheckBox、ToggleButton 都繼承自 android.widget.CompoundButton,而 CompoundButton 又繼承自 Button。它在 Button 基礎上封裝了一個 checked 狀態,這正是三者有別於普通按鈕的核心所在,且用法完全一致:
RadioButton 通常與 RadioGroup 搭配使用。同一個 RadioGroup 內的所有單選鈕互斥,恆有且僅有一個處於選中態;不同 RadioGroup 之間互不干擾,這一點在做多組多選題式的表單時特別有用。
下面的例子用一組單選鈕采集性別,點擊按鈕後把結果彈出提示。
布局代碼:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="Gender:" />
- <!-- 定義一個RadioGroup用於包裝RadioButton -->
- <RadioGroup
- android:id="@+id/gender"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" >
- <RadioButton
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="male" />
- <RadioButton
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="female" />
- </RadioGroup>
- <Button
- android:id="@+id/btnGender"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="選擇性別" />
- </LinearLayout>
實現代碼:
- package com.example.changebutton;
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.Button;
- import android.widget.RadioButton;
- import android.widget.RadioGroup;
- import android.widget.Toast;
- public class RadioButtonActivity extends Activity {
- private RadioGroup group;
- private Button btnGender;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- // TODO Auto-generated method stub
- super.onCreate(savedInstanceState);
- setContentView(R.layout.radiobutton_layout);
- group = (RadioGroup) findViewById(R.id.gender);
- btnGender = (Button) findViewById(R.id.btnGender);
- btnGender.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- // 獲取單選按鈕的選項個數
- int len = group.getChildCount();
- String msgString = "";
- for (int i = 0; i < len; i++) {
- //RadioGroup中包含的子View就是一個RadioButton
- RadioButton radiobutton = (RadioButton) group.getChildAt(i);
- if (radiobutton.isChecked()) {
- //如果被選中,則break循環,並且記錄選中信息
- msgString = "You choose to be a "
- + radiobutton.getText().toString();
- break;
- }
- }
- if (msgString.equals("")) {
- Toast.makeText(RadioButtonActivity.this,
- "Please select a gender!", Toast.LENGTH_SHORT)
- .show();
- }
- else {
- Toast.makeText(RadioButtonActivity.this, msgString,
- Toast.LENGTH_SHORT).show();
- }
- }
- });
- }
- }
取值時遍歷 RadioGroup 的子 View 即可,因為互斥關係,最多只有一個 isChecked() 為真,找到後直接跳出循環。實戰中也可以用 getCheckedRadioButtonId() 更直接地拿到 ID。
CheckBox 與 RadioButton 用法相似,關鍵差異是支持多選,因此不需要外層容器。這個示例順帶演示 Android 動態添加控件的兩種正統做法:
示例用 chooseMethod(boolean) 參數在兩種方式間切換,便於對照。
布局代碼:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical"
- android:id="@+id/checkLayout">
- <!-- 這裡只是定義了一個按鈕,其他的CheckBox控件在代碼中動態添加 -->
- <Button
- android:id="@+id/checkBtn"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="確定" />
- </LinearLayout>
若採用動態填充方式,還需一個 CheckBox 的獨立 XML:
- <?xml version="1.0" encoding="utf-8"?>
- <CheckBox xmlns:android="https://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" >
- </CheckBox>
實現代碼:
- package com.example.changebutton;
- import java.util.ArrayList;
- import java.util.List;
- import android.app.Activity;
- import android.app.AlertDialog;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.CheckBox;
- import android.widget.LinearLayout;
- public class CheckBoxActivity extends Activity implements OnClickListener {
- private List<CheckBox> checkBoxs = new ArrayList<CheckBox>();
- private Button checkBtn;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- chooseMethod(false);
- checkBtn = (Button) findViewById(R.id.checkBtn);
- checkBtn.setOnClickListener(this);
- }
- @Override
- public void onClick(View v) {
- String s = "";
- //循環cheackBoxs
- for (CheckBox c : checkBoxs) {
- if (c.isChecked()) {
- //如果選中就添加選中結果到msg中
- s += c.getText() + "\n";
- }
- }
- if ("".equals(s)) {
- s = "您沒有選中選項!";
- }
- //使用對話框彈出選中的信息
- new AlertDialog.Builder(this).setMessage(s)
- .setPositiveButton("Exit", null).show();
- }
- private void chooseMethod(boolean b) {
- String[] checkboxText = new String[]{"You are student?",
- "Do you like Android?","Do you have a girlfriend",
- "Do you like online shopping?"};
- if (b) {
- //使用本文中提到的第一種方式,通過Id動態加載
- setContentView(R.layout.checkbox_layout);
- //獲取帶填充的布局控件
- LinearLayout linearLayout = (LinearLayout) this
- .findViewById(R.id.checkLayout);
- //根據數組,循環添加內容
- for (int i = 0; i < checkboxText.length; i++) {
- CheckBox checkbox = new CheckBox(this);
- checkBoxs.add(checkbox);
- checkBoxs.get(i).setText(checkboxText[i]);
- //把CheckBox加入到布局控件中
- linearLayout.addView(checkbox);
- }
- }
- else {
- //通過動態填充的方式,找到布局文件
- LinearLayout linearLayout = (LinearLayout) getLayoutInflater()
- .inflate(R.layout.checkbox_layout, null);
- for (int i = 0; i < checkboxText.length; i++) {
- //在通過動態填充的方式找到CheckBox的文件
- CheckBox checkbox = (CheckBox) getLayoutInflater().inflate(
- R.layout.cheackbox, null);
- checkBoxs.add(checkbox);
- checkBoxs.get(i).setText(checkboxText[i]);
- linearLayout.addView(checkbox);
- }
- //最後把這個布局文件加載顯示
- setContentView(linearLayout);
- }
- }
- }
收集結果時把每個 CheckBox 存進 List 統一遍歷,比反覆 findViewById 清爽得多;一個都不選的情況也要記得給用戶提示。
ToggleButton 是一個帶開關語義的按鈕,兩個狀態各自可配文案:
它提供 setOnCheckedChangeListener(),傳入 OnCheckedChangeListener 接口實現,狀態切換時觸發 onCheckedChange()。這個接口來自 CompoundButton,因此 RadioButton、CheckBox 也能用它做即時響應。
下面的示例用一個 ToggleButton 控制 LinearLayout 在橫向與縱向排列之間切換。
布局代碼:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
- <ToggleButton
- android:id="@+id/togBtn"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:checked="true"
- android:textOff="橫向排列"
- android:textOn="縱向排列" />
- <LinearLayout
- android:id="@+id/OriLayout"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
- <Button
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="btn1" />
- <Button
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="btn2" />
- <Button
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="btn3" />
- </LinearLayout>
- </LinearLayout>
實現代碼:
- package com.example.changebutton;
- import android.app.Activity;
- import android.os.Bundle;
- import android.widget.CompoundButton;
- import android.widget.CompoundButton.OnCheckedChangeListener;
- import android.widget.LinearLayout;
- import android.widget.ToggleButton;
- public class ToggleButtonActivity extends Activity {
- private ToggleButton togBtn;
- private LinearLayout linearLayout;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- // TODO Auto-generated method stub
- super.onCreate(savedInstanceState);
- setContentView(R.layout.toggle_layout);
- togBtn = (ToggleButton) findViewById(R.id.togBtn);
- linearLayout = (LinearLayout) this.findViewById(R.id.OriLayout);
- togBtn.setOnCheckedChangeListener(new OnCheckedChangeListener() {
- @Override
- public void onCheckedChanged(CompoundButton buttonView,
- boolean isChecked) {
- //通過判斷是否選中,來設置LinearLayout的橫向縱向排列
- if (isChecked) {
- linearLayout.setOrientation(1);
- }
- else {
- linearLayout.setOrientation(0);
- }
- }
- });
- }
- }
小提示:setOrientation 傳 0 為橫向、1 為縱向,用常量 LinearLayout.HORIZONTAL / VERTICAL 可讀性更好。
三個控件共享 CompoundButton 的 checked 狀態,區別只在選擇語義與專屬屬性。Android 4.0 之後還新增了 Switch 控件,用法與這三者幾乎一致,這裡不再展開。
Android記事本範例剖析(二):選項、上下文與動態選單
本篇繼續以記事本範例說明 Android 的選單系統。Android 主要提供三種選單:選項選單、上下文選單與子選單。理解它們的呼叫時機,是做出順手操作介面的基礎。 An
Android 記事本示例剖析(四):NoteEditor 類與 Content Provider 機制
在前一篇中,我們研究了 Activity 的生命週期、狀態轉換機制以及自定義控件。本文延續記事本示例的分析,重點拆解 NoteEditor 類與 Content Prov
Android MediaPlayer 音訊播放實戰
Android 提供了多種控制音訊與影片播放的方式,不論是播放本機檔案或串流來源都能應付,而其中最典型的做法就是使用 MediaPlayer 類別。 Android 透過
Android 應用本地化實作教學
Android 應用往往會在多個國家、各種裝置上運行,使用者來自不同語言背景。要讓應用更具親和力,就必須針對當前語言環境妥善處理文字、數字、檔案等內容,這便是本地化的目標