iT邦幫忙

2021 iThome 鐵人賽

DAY 18
0
Mobile Development

Android Studio 30天自我挑戰系列 第 18

[Android Studio 30天自我挑戰] ToggleButton元件介紹

ToggleButton為開關按鈕,也就是說點一下就顯示開啟再點一下就顯示關閉。

ToggleButton常用的方法

1.setTextOn當按鈕按下時的文字
2.setTextOff當按鈕未選取時的文字
3.setChecked設定按紐按下後的狀態
4.setBackgroundDrawable設定按紐背景圖案
5.setOnCheckedChangeListener設定按紐狀態監聽器

例如按下ToggleButton後TextView顯示ToggleButton目前關閉還是開啟
xml檔如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >
    <ToggleButton
        android:id="@+id/toggleButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="100dp"
        android:textOff="關閉"
        android:textOn="開啟"
        android:textSize="30dp" />
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text=""
        android:textSize="30dp" />
</LinearLayout>

透過setOnCheckedChangeListener來抓取目前狀態
MainActivity.java範例:

package com.example.ittogglebtn;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;

import org.w3c.dom.Text;

public class MainActivity extends AppCompatActivity {
    ToggleButton toggleButton;
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toggleButton = findViewById(R.id.toggleButton);
        textView = findViewById(R.id.textView);
        toggleButton.setOnCheckedChangeListener(new Toggle());
    }
    private class Toggle implements CompoundButton.OnCheckedChangeListener{
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(isChecked)
            {
                textView.setText("ToggleButton開啟");
            }
            else {
                textView.setText("ToggleButton關閉");
            }
        }
    }
}

APP畫面:
https://ithelp.ithome.com.tw/upload/images/20211003/20139258GRdz0PmpXy.png
https://ithelp.ithome.com.tw/upload/images/20211003/20139258LT8uw6LVte.png


上一篇
[Android Studio 30天自我挑戰] Radiobutton和Checkbox的練習
下一篇
[Android Studio 30天自我挑戰] 透過Banner來輪播廣告資訊
系列文
Android Studio 30天自我挑戰30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言