[Android]开关控件Switch

导读:本篇文章讲解 [Android]开关控件Switch,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

效果图:

关闭:

[Android]开关控件Switch

 打开:

[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()}
            }
        }

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由半码博客整理,本文链接:https://www.bmabk.com/index.php/post/95949.html

(0)
小半的头像小半

相关推荐

半码博客——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!