[Android]开关控件Switch

效果图:

关闭:

 打开:

<Switch
        android:id="@+id/switch1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true"
        android:track="@drawable/selector"
        android:thumb="@drawable/rbzhong"
        />

selector.xml 

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:drawable="@drawable/shape1" android:state_checked="true"/>
  <item android:drawable="@drawable/shape2" android:state_checked="false"/>

</selector>

 shape1.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="45dp"/>
    <stroke android:width="2dp" android:color="#ff99cc"/>
    <gradient android:startColor="#ffcccc" android:centerColor="#ff6699" android:endColor="#ff3399"></gradient>
</shape>

 shape2.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@color/white"/>
      <corners android:radius="45dp"/>
    <stroke android:width="2dp" android:color="#ff99cc"/>
</shape>

switch的属性

XML 属性
android:switchMinWidth开关组件的最小宽度。
android:switchPadding开关和标题文本之间的最小间距。
android:switchTextAppearance文本切换拇指上显示的文本的外观样式。
android:textOff交换机处于未选中/“关闭”状态时使用的文本。
android:textOn交换机处于选中/“打开”状态时要使用的文本。
android:thumb可绘制用作来回切换的“拇指”。
android:thumbTextPadding切换拇指内文本两侧的填充量。
android:track可绘制用作切换拇指在其中滑动的“轨道”。

 事件监听

        val switch1:Switch=findViewById(R.id.switch1)
        switch1.setOnCheckedChangeListener { buttonView, isChecked ->
            when(isChecked){
                true->{Toast.makeText(this,"true",Toast.LENGTH_SHORT).show()}
                false->{Toast.makeText(this,"false",Toast.LENGTH_SHORT).show()}
            }
        }

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值