Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

ToggleButton 用法整理:一個開燈關燈的小範例

編輯:關於 Android 開發

ToggleButton 是兩狀態的按鈕——選中與未選中,而且能為兩種狀態分別指定顯示文字,這點比一般 Button 好用。實務上最常見的應用就是開關切換,例如燈泡圖片對應開/關兩張圖。

版面檔 main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <ImageView android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/bulb_off"
        android:layout_gravity="center_horizontal" />

    <ToggleButton android:id="@+id/toggleButton"
        android:layout_width="140dip"
        android:layout_height="wrap_content"
        android:textOn="開燈"
        android:textOff="關燈"
        android:layout_gravity="center_horizontal" />
</LinearLayout>

關鍵屬性就是 android:textOn 與 android:textOff:開啟時顯示前者,關閉時顯示後者,不需要自己在程式碼裡切字串。

ToggleButtonActivity

package com.ljq.tb;

import android.app.Activity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ToggleButton;

public class ToggleButtonActivity extends Activity {

    private ImageView imageView = null;
    private ToggleButton toggleButton = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        imageView = (ImageView) findViewById(R.id.imageView);
        toggleButton = (ToggleButton) findViewById(R.id.toggleButton);

        toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                imageView.setImageResource(isChecked ? R.drawable.bulb_on : R.drawable.bulb_off);
            }
        });
    }
}

幾個容易忽略的細節

監聽器用的是 OnCheckedChangeListener(來自 CompoundButton),不是 OnClickListener;兩者都能用,但要判斷狀態時前者直觀得多。

另外,監聽器裡的那行 toggleButton.setChecked(isChecked) 有多餘之嫌——狀態已經變了,再設一次只會觸發第二次回呼,容易寫出無限遞迴的程式碼,記得移除。

若要在程式碼中預設狀態,用 setChecked(true);但要注意在設定監聽器「之前」設初始值,否則一註冊就會被回呼一次,造成非預期的副作用。至於外觀,XML 的 android:background 搭配 selector 或 drawableTop 都能替換預設樣式,新版專案則可考慮 Material 的 SwitchMaterial 或 MaterialSwitch,語意與無障礙支援都更完整。

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