Android自定义View----开关按钮

本文介绍如何在Android中自定义一个开关按钮(SwitchButton),包括布局设计、状态切换逻辑及触摸事件处理等关键技术点。

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

在coding的过程中需要用到简单的switch-button,因为Android自带库没有此组件,使用就打算自定义view实现一个开关按钮。
  我使用了view的组合,首先思考开关按钮的组成,分为2个部分,一个是底部的圆角矩形,一部分是在开关过程中顶部变换的图片。
  于是写出按钮的xml布局

layout_switch.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <View
        android:id="@+id/view_scroll"
        android:layout_width="60dp"
        android:layout_height="30dp"
        android:background="@drawable/switch_button_selector"/>

</RelativeLayout>
自定义图片选择器:switch_button_selector.xml

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

接下来,我们给SwitchButton自定义一个属性,defaultStatus,即默认属性,即应用启动的时候该按钮的默认状态,分为open和close。
 在res/values目录下新建attrs.xml文件,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="SwitchButton">
        <attr name="defaultStatus">
            <enum name="open" value="1" />
            <enum name="close" value="0" />
        </attr>
    </declare-styleable>
</resources>
接着,就可以在java代码中定义我们的SwitchButton组件
新建一个类SwitchButton.java和一个接口OnSwitchListener.java

public class SwitchButton extends RelativeLayout {
    public static final int OPEN = 1;
    public static final int CLOSE = 0;

    private int defaultStatus;

    private int currentStatus;
    private OnSwitchListener onSwitchListener;

    private TypedArray typedArray;

    private View view;

    public SwitchButton(Context context) {
        super(context);
    }

    public SwitchButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.layout_switch, this);
        typedArray = context.obtainStyledAttributes(attrs, R.styleable.SwitchButton);
        initView();
        init();
    }

    /**
     * 初始化控件
     */
    private void initView() {
        view = findViewById(R.id.view_scroll);
    }

    /**
     * 初始化操作
     */
    private void init() {
        defaultStatus = typedArray.getInt(R.styleable.SwitchButton_defaultStatus, 1);
        if (defaultStatus == 0) {
            view.setBackgroundResource(R.drawable.switch_off);
            setViewLocation(view, RelativeLayout.ALIGN_PARENT_LEFT);
            currentStatus = CLOSE;
        } else if (defaultStatus == 1) {
            view.setBackgroundResource(R.drawable.switch_on);
            setViewLocation(view, RelativeLayout.ALIGN_PARENT_RIGHT);
            currentStatus = OPEN;
        }
    }

    private void setViewLocation(View view, int location) {
        LayoutParams layoutParams = (LayoutParams) view.getLayoutParams();
        if (location == RelativeLayout.ALIGN_PARENT_LEFT) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                layoutParams.removeRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            }
        } else if (location == RelativeLayout.ALIGN_PARENT_RIGHT) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                layoutParams.removeRule(RelativeLayout.ALIGN_PARENT_LEFT);
            }
        }
        layoutParams.addRule(location);
        view.setLayoutParams(layoutParams);
    }

    /**
     * 获取当前的状态
     */
    public int getCurrentStatus() {
        return currentStatus;
    }

    /**
     * 设置状态变化监听
     */
    public void setOnSwitchListener(OnSwitchListener onSwitchListener) {
        this.onSwitchListener = onSwitchListener;
    }

    /**
     * 关闭按钮
     */
    private void closeButton() {
        view.setBackgroundResource(R.drawable.switch_off);
        setViewLocation(view, RelativeLayout.ALIGN_PARENT_LEFT);
        currentStatus = CLOSE;
    }

    /**
     * 打开按钮
     */
    private void openButton() {
        view.setBackgroundResource(R.drawable.switch_on);
        setViewLocation(view, RelativeLayout.ALIGN_PARENT_RIGHT);
        currentStatus = OPEN;
    }

    /**
     * 改变状态
     */
    private void changeStatus() {
        if (currentStatus == OPEN) {
            closeButton();
        } else if (currentStatus == CLOSE) {
            openButton();
        }
        if (onSwitchListener != null) {
            onSwitchListener.onSwitchChange();  //调用监听改变时候处理逻辑的函数
        }
    }

    /**
     * 触摸事件
     * 触摸一下,改变按钮的状态
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                /**
                 * 改变状态
                 */
                changeStatus();
                break;
            default:
                break;
        }
        return super.onTouchEvent(event);
    }
    public interface OnSwitchListener {
        void onSwitchChange();
    }
}
在MainActivity的布局文件activity_main.xml文件中添加布局:

<com.danale.video.util.SwitchButton
                android:id="@+id/sb_setting_switch1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:layout_marginRight="@dimen/dp30"
                app:defaultStatus="close" />
在MainActivity中实例化控件,并设置OnSwitchListener监听并实现回调方法,具体过程如下:

switchDeviceNotice = (SwitchButton) findViewById(R.id.sb_setting_switch1);

switchDeviceNotice.setOnSwitchListener(new SwitchButton.OnSwitchListener() {
            @Override
            public void onSwitchChange() {
            }
        });
效果运行图如下:

文章参考于:http://blog.youkuaiyun.com/u014044853/article/details/51299116

http://blog.youkuaiyun.com/l1028386804/article/details/48102871

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值