ToggleButton和Switch

本文介绍了状态开关组件ToggleButton和Switch的基本用法及特性。这两种组件都继承自Button,并且支持其所有属性。文章通过一个示例应用程序展示了如何设置开关组件的状态文本、如何监听状态改变并进行响应操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

状态开关按钮(ToggleButton)与开关(Switch)都是继承Button的。
它们支持Button的各种属性。
它们常用在切换程序中的某种状态。
特有属性:
android:textOff 设置当前按钮关闭时显示的文本
android:textOn 设置当前按钮打开时显示的文本
android:thumb 使用自定义的Drawable绘制开关按钮(switch特有的)

package com.xspacing.togglebuttonandswitch;

import android.app.Activity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Switch;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends Activity {

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

    private void initViews() {
        ToggleButton tb = (ToggleButton) findViewById(R.id.main_toggle);
        Switch mSwitch = (Switch) findViewById(R.id.swich);
        tb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                String str = null;
                str = isChecked ? "开关开启" : "开关关闭";
                Toast.makeText(getApplicationContext(), str, 0).show();
            }
        });

        mSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                String str = null;
                str = isChecked ? "开关开启" : "开关关闭";
                Toast.makeText(getApplicationContext(), str, 0).show();
            }
        });

    }

}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.xspacing.togglebuttonandswitch.MainActivity" >

    <ToggleButton
        android:id="@+id/main_toggle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textOff="off"
        android:textOn="on" />

    <Switch
        android:id="@+id/swich"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值