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

Android 學習筆記(十三):ToggleButton 開關控件的使用

編輯:關於 Android 開發

Android 學習筆記(十三):ToggleButton 開關控件的使用

ToggleButton 顧名思義是一個「開關」控件,具有兩種不同狀態(開與關)。它有三個主要特有屬性:

  • android:textOn="開":狀態為 true 時顯示的文字
  • android:textOff="關":狀態為 false 時顯示的文字
  • android:checked="true":標識是否被選中

以下用一個簡單例子說明:用 ToggleButton 的狀態控制 TextView 顯示不同文字。

布局檔

<ToggleButton
    android:id="@+id/toggleButton1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:textOn="開"
    android:textOff="關"
    android:checked="true"/>
<!-- android:checked 標識是否被選中,若未寫則默認未選中 -->

<TextView
    android:id="@+id/textView1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/toggleButton1"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/toggleButton1"
    android:layout_marginTop="31dp" />

源碼

透過 setOnCheckedChangeListener 監聽狀態變化,依開關狀態顯示不同文字:

private ToggleButton tgB;
private TextView tV;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tgB = (ToggleButton) findViewById(R.id.toggleButton1);
    tV = (TextView) findViewById(R.id.textView1);

    tgB.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // 依不同狀態顯示不同文字
            if (isChecked) {
                tV.setText("此時狀態為開");
                tV.setTextSize(30f);
            } else {
                tV.setText("此時狀態為關");
                tV.setTextSize(30f);
            }
        }
    });
}

運行效果:

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