Photo by National Cancer Institute on Unsplash
[Switch]
Switch 狀態開關按鈕的功能,就跟一般家裡的開關一樣,有開啟與關閉兩種狀態,跟先前認識的 CheckBox 功能類似,也是繼承自 Button 類別,使用者可以來回拖動開關中的圓點,輕按控制該按鈕的開啟與關閉。在Android 中,Switch 元件經常被使用在 APP 的設置介面中。例如,WIFI 開關、藍芽開關等功能。如要使用 Switch,可在 Layout 佈局檔 XML 中使用 <Switch> 標記來設定,語法格式如下:<Switch android:屬性 = "值"> </Switch>Switch 狀態開關支援的 XML 屬性很多,較常用的屬性表列如下:
| XML屬性 | 描 述 |
|---|---|
| switchMinWidth | 設定 Switch 元件的最小寬度。 |
| switchPadding | 設定 Switch 元件與左側標題之間的距離 |
| switchTextAppearance | 設定標題的樣式。 |
| textOff | 設定 Switch 關閉時顯示的文字。 |
| textOn | 設定 Switch 開啟時顯示的文字。 |
| textStyle | 設定字體的樣式(普通,粗體,斜體,粗體)。 |
| showText | 設定 Switch 打開或關閉時是否顯示文字。 |
| splitTrack | 是否設置一個間隙,讓滑塊與底部圖片分隔。 |
| track | 設定開關滑動的軌道。 |
| textStyle | 設定的文字風格。 |
| thumb | 設定切換開關的圖示。 |
| track | 設定開關滑動的軌道。 |
| typeface | 設定字體,預設支援:sans, serif, monospace三種。 |
[程式範例]
(1)新建一個模組 Module,進入 res/layout 目錄下點選佈局檔 activity_main.xml。將預設的內容刪除,建立 1 個 Switch 設定開關,以下是整個 XML 的內容。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Switch
android:id="@+id/sw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50sp"
android:layout_marginTop="50sp"
android:switchPadding="100sp"
android:text="開啟無線網路 WiFi" />
</RelativeLayout>
(2)在 MainActivity.java 在 onCreate() 方法內,先建立與佈局檔的物件,用 findValueById 連結元件,建立一個 setOnCheckedChangeListener 監聽器,然後重寫onCheckedChanged() 事件,判斷 Switch 是否被選中,再使用 Toast 顯示訊息在畫面上。程式碼如下:
package com.example.myswitch;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.Toast;
public class sw_MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sw_main);
Switch sw = (Switch) findViewById(R.id.sw); //獲得佈局 Layout 中的元件
sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (sw.isChecked()) { // 判斷開關是否被選中
Toast.makeText(sw_MainActivity.this, "開啟 WiFi 無線網路...", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(sw_MainActivity.this, "關閉 WiFi 無線網路...", Toast.LENGTH_LONG).show();
}
}
});
}
}
[參考資料]
- Developer : Switch
- 明日科技:Android 從入門到精通

張貼留言