Android 高仿IOS打开和关闭按钮

本文介绍了一种在Android应用中创建美观自定义开关的方法。通过使用系统的Switch控件并自定义thumb和track背景,可以轻松实现不同的视觉效果。文中提供了XML代码示例,包括如何设置不同状态下的轨道颜色及监听开关状态变化。

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

一、废话不多说,先上图

二、实现思路

如果你们的效果要求不是太严苛,你可以使用这种方式。看起来还是挺美观和漂亮的。

1、使用系统的Switch控件,然后设置thumb和track背景就能实现

2、然后监听setOnCheckedChangeListener就能知道打开和关闭

三、代码

activity.xml

<Switch
        android:id="@+id/activity_setServe_switch_open"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textOff=""
        android:layout_marginTop="100dp"
        android:layout_marginLeft="100dp"
        android:textOn=""
        android:thumb="@drawable/switch_thumb"
        android:track="@drawable/switch_track" />
switch_thumb.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <size
        android:width="30dp"
        android:height="30dp">
    </size>
    <solid
        android:color="@android:color/white">
    </solid>

</shape>

switch_track.xml


<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:state_checked="true"
        android:drawable="@drawable/switch_track_on"/>
    <item
        android:state_checked="false"
        android:drawable="@drawable/switch_track_off"/>
</selector>

switch_track_off.xml


<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid
        android:color="#e4e4e4">
    </solid>
    <corners
        android:radius="30dp">
    </corners>
</shape>
switch_track_on.xml


<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <solid
        android:color="#00ABEC">
    </solid>

    <corners
        android:radius="32dp">
    </corners>

</shape>

最后设置监听事件

 ((Switch)findViewById(R.id.activity_setServe_switch_open)).
                setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    Toast.makeText(MainActivity.this,"打开",Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(MainActivity.this,"关闭",Toast.LENGTH_LONG).show();
                }
            }
        });



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值