ios风格的开关按钮(支持圆形和矩形风格)

原创 2016年08月30日 13:42:15

源码:

package com.bruce.myapplicationtst;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Looper;
import android.os.Parcelable;
import android.support.v4.view.MotionEventCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;

/**
 * Created by Administrator on 2016/8/30 0030.
 */

public class SlideSwitch extends View {

    private static final String TAG = SlideSwitch.class.getSimpleName();

    public static final int SHAPE_RECT = 1;
    public static final int SHAPE_CIRCLE = 2;
    private static final int RIM_SIZE = 6;
    private static final int DEFAULT_COLOR_THEME = Color.parseColor("#ff00ee00");
    // 3 attributes
    private int color_theme;
    private boolean isOpen;
    private int shape;
    // varials of drawing
    private Paint paint;
    private Rect backRect;
    private Rect frontRect;
    private RectF frontCircleRect;
    private RectF backCircleRect;
    private int alpha;
    private int max_left;
    private int min_left;
    private int frontRect_left;
    private int frontRect_left_begin = RIM_SIZE;
    private int eventStartX;
    private int eventLastX;
    private int diffX = 0;
    private boolean slideable = true;
    private SlideListener listener;

    public interface SlideListener {
        public void open();

        public void close();
    }

    public SlideSwitch(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        listener = null;
        paint = new Paint();
        paint.setAntiAlias(true);
        TypedArray a = context.obtainStyledAttributes(attrs,
                com.leaking.slideswitch.R.styleable.slideswitch);
        color_theme = a.getColor(com.leaking.slideswitch.R.styleable.slideswitch_themeColor,
                DEFAULT_COLOR_THEME);
        isOpen = a.getBoolean(com.leaking.slideswitch.R.styleable.slideswitch_isOpen, false);
        shape = a.getInt(com.leaking.slideswitch.R.styleable.slideswitch_shape, SHAPE_RECT);
        a.recycle();
    }

    public SlideSwitch(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SlideSwitch(Context context) {
        this(context, null);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int defaultWidth = dp2px(getContext(), 60);
        int defaultHeight = dp2px(getContext(), 30);
        int width = measureDimension(defaultWidth, widthMeasureSpec);
        int height = measureDimension(defaultHeight, heightMeasureSpec);
        if (shape == SHAPE_CIRCLE) {
            if (width < height)
                width = height * 2;
        }
        setMeasuredDimension(width, height);
        initDrawingVal();
    }

    public void initDrawingVal() {
        int width = getMeasuredWidth();
        int height = getMeasuredHeight();

        backCircleRect = new RectF();
        frontCircleRect = new RectF();
        frontRect = new Rect();
        backRect = new Rect(0, 0, width, height);
        min_left = RIM_SIZE;
        if (shape == SHAPE_RECT)
            max_left = width / 2;
        else
            max_left = width - (height - 2 * RIM_SIZE) - RIM_SIZE;
        if (isOpen) {
            frontRect_left = max_left;
            alpha = 255;
        } else {
            frontRect_left = RIM_SIZE;
            alpha = 0;
        }
        frontRect_left_begin = frontRect_left;
    }

    public int measureDimension(int defaultSize, int measureSpec) {
        int result;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);
        if (specMode == MeasureSpec.EXACTLY) {
            result = specSize;
        } else {
            result = defaultSize; // UNSPECIFIED
            if (specMode == MeasureSpec.AT_MOST) {
                result = Math.min(result, specSize);
            }
        }
        return result;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (shape == SHAPE_RECT) {
            //背景色
            paint.setColor(Color.GRAY);
            canvas.drawRect(backRect, paint);
            paint.setColor(color_theme);
            paint.setAlpha(alpha);
            canvas.drawRect(backRect, paint);
            frontRect.set(frontRect_left, RIM_SIZE, frontRect_left
                    + getMeasuredWidth() / 2 - RIM_SIZE, getMeasuredHeight()
                    - RIM_SIZE);
            paint.setColor(Color.WHITE);
            canvas.drawRect(frontRect, paint);
        } else {
            // draw circle
            int radius;
            radius = backRect.height() / 2 - RIM_SIZE;
            //背景色
            paint.setColor(Color.RED);
            backCircleRect.set(backRect);
            canvas.drawRoundRect(backCircleRect, radius, radius, paint);
            paint.setColor(color_theme);
            paint.setAlpha(alpha);
            canvas.drawRoundRect(backCircleRect, radius, radius, paint);
            frontRect.set(frontRect_left, RIM_SIZE, frontRect_left
                    + backRect.height() - 2 * RIM_SIZE, backRect.height()
                    - RIM_SIZE);
            frontCircleRect.set(frontRect);
            paint.setColor(Color.WHITE);
            canvas.drawRoundRect(frontCircleRect, radius, radius, paint);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (slideable == false) {
            Log.i(TAG, "onTouchEvent slideable = false");
            return super.onTouchEvent(event);
        }
        int action = MotionEventCompat.getActionMasked(event);
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                eventStartX = (int) event.getRawX();
                break;
            case MotionEvent.ACTION_MOVE:
                eventLastX = (int) event.getRawX();
                diffX = eventLastX - eventStartX;
                int tempX = diffX + frontRect_left_begin;
                tempX = (tempX > max_left ? max_left : tempX);
                tempX = (tempX < min_left ? min_left : tempX);
                if (tempX >= min_left && tempX <= max_left) {
                    frontRect_left = tempX;
                    alpha = (int) (255 * (float) tempX / (float) max_left);
                    invalidateView();
                }
                break;
            case MotionEvent.ACTION_UP:
                int wholeX = (int) (event.getRawX() - eventStartX);
                frontRect_left_begin = frontRect_left;
                boolean toRight;
                toRight = (frontRect_left_begin > max_left / 2 ? true : false);
                if (Math.abs(wholeX) < 3) {
                    toRight = !toRight;
                }
                moveToDest(toRight);
                break;
            default:
                break;
        }
        return true;
    }

    /**
     * draw again
     */
    private void invalidateView() {
        if (Looper.getMainLooper() == Looper.myLooper()) {
            invalidate();
        } else {
            postInvalidate();
        }
    }

    public void setSlideListener(SlideListener listener) {
        this.listener = listener;
    }

    public void moveToDest(final boolean toRight) {
        ValueAnimator toDestAnim = ValueAnimator.ofInt(frontRect_left,
                toRight ? max_left : min_left);
        toDestAnim.setDuration(300);
        toDestAnim.setInterpolator(new AccelerateDecelerateInterpolator());
        toDestAnim.start();
        setSlideable(false);
        toDestAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                frontRect_left = (Integer) animation.getAnimatedValue();
                alpha = (int) (255 * (float) frontRect_left / (float) max_left);
                invalidateView();
            }
        });
        toDestAnim.addListener(new AnimatorListenerAdapter() {

            @Override
            public void onAnimationEnd(Animator animation) {
                setSlideable(true);
                if (toRight) {
                    if (listener != null && isOpen == false)
                        listener.open();
                    isOpen = true;
                    frontRect_left_begin = max_left;
                } else {
                    if (listener != null && isOpen == true)
                        listener.close();
                    isOpen = false;
                    frontRect_left_begin = min_left;
                }
            }
        });
    }

    public void setState(boolean isOpen) {
        this.isOpen = isOpen;
        initDrawingVal();
        invalidateView();
        if (listener != null)
            if (isOpen == true) {
                listener.open();
            } else {
                listener.close();
            }
    }

    public void setShapeType(int shapeType) {
        this.shape = shapeType;
    }

    public void setSlideable(boolean slideable) {
        this.slideable = slideable;
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        if (state instanceof Bundle) {
            Bundle bundle = (Bundle) state;
            this.isOpen = bundle.getBoolean("isOpen");
            state = bundle.getParcelable("instanceState");
        }
        super.onRestoreInstanceState(state);
    }

    @Override
    protected Parcelable onSaveInstanceState() {
        Bundle bundle = new Bundle();
        bundle.putParcelable("instanceState", super.onSaveInstanceState());
        bundle.putBoolean("isOpen", this.isOpen);
        return bundle;
    }

    /**
     * dp转px
     *
     * @param context
     * @param dpVal
     * @return
     */
    public static int dp2px(Context context, float dpVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                dpVal, context.getResources().getDisplayMetrics());
    }
}


  <declare-styleable name="slideswitch">
        <attr name="themeColor" format="color" />
        <attr name="isOpen" format="boolean" />
        <attr name="shape">
            <enum name="rect" value="1" />
            <enum name="circle" value="2" />
        </attr>
    </declare-styleable>



使用方法:

   SlideSwitch slideSwitch = (SlideSwitch) findViewById(R.id.button);
        slideSwitch.setSlideListener(new SlideSwitch.SlideListener() {

            @Override
            public void open() {
                // Do something ,,,
                Toast.makeText(MainActivity.this, "open", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void close() {
                // Do something ,,,
                Toast.makeText(MainActivity.this, "close", Toast.LENGTH_SHORT).show();
            }
        });

        <com.bruce.myapplicationtst.SlideSwitch
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            slideswitch:isOpen="false"
            android:layout_margin="5dp"
            slideswitch:shape="circle"
            slideswitch:themeColor="#f200aa96" />


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

单元格左侧附带选择按钮

这是之前足球兄弟项目里实现的一个效果,联系人左侧有一个附带的选择按钮,点击可选中,再次点击取消选中。很简单的一个效果,由于当时工作经验不做,第一想法是在单元格的左侧添加按钮,设置按钮在选中和未选中状态...

iOS画圆角矩形的方法

1.CGContextAddArcToPoint +(void)drawRoundRectInContext:(CGContextRef)context withRect:(CG...

android仿IOS风格的开关按钮

  • 2016年05月23日 16:36
  • 96KB
  • 下载

CSS---checkbox美化,ios风格的开关按钮

CSS---checkbox美化,ios风格的开关按钮这段时间工作的新需求,是做一个类似IOS开关按钮。用来显示是否选中。 如: 默认未选中 默认选中CSS中通过:before、:after...
  • J_Y_X_8
  • J_Y_X_8
  • 2016年04月19日 16:38
  • 920

Android 自定义View学习(3)--仿IOS风格滑动按钮

谢谢收看自定义学习的第三期

QML实现安卓风格开关按钮

  • 2016年10月25日 16:51
  • 2KB
  • 下载

ios风格的滑动开关

  • 2015年11月18日 15:31
  • 2.05MB
  • 下载

IOS7风格弹出框-支持block回调

已经很长一段时间没有更新博客了,今天写了个弹出框,主要用于SDK里面 现贴出来分享下: #import @interface SYTipView : NSObject + (SYTipView *...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:ios风格的开关按钮(支持圆形和矩形风格)
举报原因:
原因补充:

(最多只允许输入30个字)