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

Android ToggleButton 控件使用詳解

編輯:Android 開發實例

ToggleButton 是一個具備兩種狀態的開關按鈕——選中與未選中,並且能為不同狀態設置不同的顯示文本,非常適合「開/關」這類二選一的交互場景。

布局文件 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 分別指定了選中和未選中時按鈕上顯示的文字。

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);
            }
        });
    }
}

這裡的核心是 OnCheckedChangeListener 監聽器:每當 ToggleButton 的狀態發生變化,回調便會觸發,我們根據 isChecked 的值切換圖片資源,就能做出「一鍵開關燈泡」的直觀效果。聲明式的文本配置加上命令式的狀態監聽,讓 ToggleButton 成為交互設計中的好搭檔。

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