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

Android 基本控件 ToggleButton 與 Switch 使用指南

編輯:關於 Android 程式設計

ToggleButton(開關按鈕)與 Switch(開關)講解:

一、核心屬性講解:

(1)ToggleButton

textOn:按鈕被選中時顯示的文字
textOff:按鈕未被選中時顯示的文字

ToggleButton 的狀態只有選中與未選中兩種,並且需要為不同狀態設定不同的顯示文字。

以下案例示範 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> 

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

運行效果:

(2)Switch:

android:showText:設定 on/off 時是否顯示文字,型別為 boolean
android:splitTrack:是否設定一個間隙,讓滑塊與底部圖片分隔,boolean
android:switchMinWidth:設定開關的最小寬度
android:switchPadding:設定滑塊內文字的間隔
android:textOff:按鈕未被選中時顯示的文字
android:textOn:按鈕被選中時顯示的文字
android:textStyle:文字風格,粗體、斜體、劃線等
android:track:底部的圖片
android:thumb:滑塊的圖片

這些屬性都可以自己動手逐一試試。

之前做一個藍牙開關時用到了 Switch,順手記一下用法,其實它和 Button 幾乎一樣。

佈局中:

 <Switch android:id="@+id/open" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textOff="藍牙關閉中" android:textOn="藍牙開啟中" /> 

Java 程式碼中

 open.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub if (isChecked) { mBluetoothAdapter.enable();//打開藍牙 } else { mBluetoothAdapter.disable();// 關閉藍牙 } } });

就是這樣,一看就明白了。

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