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

Android ToggleButton 控件使用詳解(開燈關燈實例)

編輯:Android 開發實例

ToggleButton 是一個只有兩種狀態的開關按鈕:選中與未選中。它最大的特點是可以為這兩種狀態分別指定顯示文字,因此非常適合用來表達「開/關」「是/否」這類二元選擇。

項目結構

一、佈局文件 main.xml

界面上放一個 ImageView 作為指示燈,下方放一個 ToggleButton,並通過 android:textOn 與 android:textOff 分別指定兩種狀態下顯示的文字。

<?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>

二、Activity 代碼

package com.ljq.tb;

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

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) {
                toggleButton.setChecked(isChecked);
                imageView.setImageResource(isChecked?R.drawable.bulb_on:R.drawable.bulb_off);
            }

        });
    }
}

三、關鍵點說明

  • 監聽 ToggleButton 狀態變化,實現的是 CompoundButton.OnCheckedChangeListener,回調方法 onCheckedChanged 會帶回一個布爾值 isChecked。
  • 利用這個布爾值做三元判斷,即可在兩張圖片資源之間切換,實現「點一下開燈、再點一下關燈」的效果。
  • 需要注意避免在監聽器裡反覆調用 setChecked() 造成遞歸觸發,本例中這樣寫是安全的,但複雜場景下建議先判斷狀態是否真的發生變化。

運行效果:

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