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

Android ToggleButton 开关按钮的完整用法详解

編輯:關於 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 則對應未選中時顯示的文字。

ToggleButtonActivity 類

復制代碼 代碼如下:

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 掛上 OnCheckedChangeListener 監聽器,就能在狀態切換時即時取得 isChecked 的布爾值,進而切換圖片資源,實現燈泡的亮滅效果。

運行效果:

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