Android组件复习之基本组件04—SwitchButton

本文详细介绍了Switch控件的基本用法及其在Android应用中的布局配置。通过实例展示了如何在布局文件中设置Switch,并通过实现CompoundButton.OnCheckedChangeListener接口来监听状态改变。

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

SwitchButton用法

1、Switch是一个可以再两种状态切换的开关控件。用户可以拖动来选择,也可以像选择复选框一样点击切换Switch的状态在布局文件使用方法同TextView:
2、该组件继承自CompoundButton,在代码中可以通过实现CompoundButton.OnCheckedChangeListener接口,并实现其内部类的onCheckedChanged来监听状态变化。

效果图
这里写图片描述

  • 不废话上代码,布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:id="@+id/da"
    android:orientation="vertical"
    android:layout_height="match_parent">

    <Switch
        android:id="@+id/switcher"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="20dp"
        android:textOff="打开片"
        android:textOn="关闭片"
        android:thumb="@drawable/check" />
</LinearLayout>
  • 类文件
import android.app.Activity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.Toast;

/**
 * Created by Administrator on 2016/9/14 0014.
 */
public class SwitchButtonActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.switch_button);
        Switch switcher = (Switch)findViewById(R.id.switcher);

        switcher.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(b){
                    Toast.makeText(SwitchButtonActivity.this,"b: "+b,Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(SwitchButtonActivity.this,"b: "+b,Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}
  • dome中的位置,记得修改dome清单中的配置,其他类都可以删除,每个类都是一个控件,没有关系

这里写图片描述


dome下载地址:http://download.youkuaiyun.com/download/bobo8945510/9631870

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值