使用自定义View做一个小开关

Android自身带的控件不能满足需求, 需要根据自己的需求定义控件.



先自定义一个Kai


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by BAIPEI on 2017/11/29.
 */

public class Kai extends View {
    private Bitmap mSwitchBackgroundBitmap;
    private Paint mPaint;
    private Bitmap mSlideSourceBitmap;
    private boolean mToogleState;
    private float mCurrentX;
    private boolean isTouchMove;
    private OnStateChangeListener mStateChangeListener;

    public Kai(Context context) {
        super(context);

    }


    public Kai(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        setSwitchBackground(0);
    }

    public Kai(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //创建一个画笔
        mPaint = new Paint();
    }
    /**
     * 添加背景
     *
     * @param switchBackground
     */
    public void setSwitchBackground(int switchBackground) {
        //把文件变为Bitmap
        mSwitchBackgroundBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.a1);
        mSlideSourceBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.a2);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //测量的方法
        setMeasuredDimension(mSwitchBackgroundBitmap.getWidth(), mSwitchBackgroundBitmap.getHeight());
    }
//super.onDraw(canvas);
    @Override
    protected void onDraw(Canvas canvas) {
        //绘制的方法
        canvas.drawBitmap(mSwitchBackgroundBitmap, 0, 0, mPaint);


        //判断是否是手指在滑动
        if (isTouchMove) {
            float newLeft = mCurrentX - mSlideSourceBitmap.getWidth() / 2;
//            canvas.drawBitmap(mSlideSourceBitmap, newLeft, 0, mPaint);

            int maxLeft = mSwitchBackgroundBitmap.getWidth()
                    - mSlideSourceBitmap.getWidth();

            // 限定滑块范围
            if (newLeft < 0) {
                newLeft = 0; // 左边范围
            } else if (newLeft > 100) {
                newLeft = 100; // 右边范围
            }

            canvas.drawBitmap(mSlideSourceBitmap, newLeft, 0, mPaint);


        } else {

            if (mToogleState) {
                canvas.drawBitmap(mSlideSourceBitmap, getWidth() - mSlideSourceBitmap.getWidth(), 0, mPaint);
            } else {
                canvas.drawBitmap(mSlideSourceBitmap, 0, 0, mPaint);
            }
        }
    }

    /**
     * 设置滑块响应触摸事件
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mCurrentX = event.getX();
                isTouchMove = true;

                break;
            case MotionEvent.ACTION_UP:
                mCurrentX = event.getX();

                isTouchMove = false;


                //根据抬起的位置设置开关值
                mToogleState = mCurrentX > mSwitchBackgroundBitmap.getWidth() / 2;

                //设置监听
                if (mStateChangeListener != null) {
                    mStateChangeListener.onStateChangeListener(mToogleState);
                }

                break;
            case MotionEvent.ACTION_MOVE:
                mCurrentX = event.getX();

                break;
            default:
                break;
        }

        Log.e("MyToggleView", "MyToggleView onTouchEvent()" + mCurrentX);

        invalidate();

        return true;
    }

    /**
     * 设置滑块
     *
     * @param slideSource
     */
    public void setSlideSource(int slideSource) {
        mSlideSourceBitmap = BitmapFactory.decodeResource(getResources(), slideSource);

    }
    /**
     * 设置开关状态
     *
     * @param toogleState
     */
    public void setToogleState(boolean toogleState) {
        mToogleState = toogleState;
    }


    public void setOnStateChangeListener(OnStateChangeListener onStateChangeListener) {
        this.mStateChangeListener = onStateChangeListener;

    }
    /**
     * 设置监听接口
     */
    public interface OnStateChangeListener {
        void onStateChangeListener(boolean toogleState);
    }
}

-------然后就是布局里面调用一下----------
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    tools:context="bwie.com.zidingyiview.MainActivity">

    <bwie.com.zidingyiview.Kai
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_width="match_parent"
        android:layout_height="80dp" />

</RelativeLayout>
最后把需要用到的两张图片发上去,

       

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,以下是一个简单的自定义开关按钮的 UniApp 组件示例: ```html <template> <view class="switch-container" @click="toggle"> <view :class="['switch', { 'on': value }]"></view> <text class="label">{{ label }}</text> </view> </template> <script> export default { props: { value: { type: Boolean, default: false }, label: { type: String, default: '' } }, methods: { toggle() { this.$emit('input', !this.value) } } } </script> <style> .switch-container { display: flex; align-items: center; margin-bottom: 10px; } .switch { width: 40px; height: 20px; border-radius: 10px; background-color: #ccc; position: relative; margin-right: 10px; transition: background-color 0.2s ease; } .switch.on { background-color: #007aff; } .switch::before { content: ''; position: absolute; top: 2px; left: 2px; width: 16px; height: 16px; border-radius: 50%; background-color: #fff; box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.2); transition: transform 0.2s ease; } .switch.on::before { transform: translateX(20px); } .label { font-size: 18px; color: #333; } </style> ``` 使用方法: ```html <template> <view> <custom-switch v-model="switchValue" label="开关"></custom-switch> </view> </template> <script> import CustomSwitch from '@/components/CustomSwitch.vue' export default { components: { CustomSwitch }, data() { return { switchValue: false } } } </script> ``` 这个组件由一个容器和一个圆形按钮组成,按钮的位置是根据组件的值来计算的。点击容器将触发 toggle 方法,该方法将使用 $emit 将新值发送到父组件,然后通过 v-model绑定到 switchValue 数据上。样式可以根据需要自行修改。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值