天天看點

android仿蘋果SwitchButton效果的實作

android仿蘋果SwitchButton效果的實作
android仿蘋果SwitchButton效果的實作
android仿蘋果SwitchButton效果的實作
android仿蘋果SwitchButton效果的實作
android仿蘋果SwitchButton效果的實作

1.建立一個類,類名就是SwitchButton

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;

public class SwitchButton extends View implements OnClickListener {

    private Bitmap mSwitchBottom, mSwitchThumb, mSwitchFrame, mSwitchMask;
    private float mCurrentX = ;
    private boolean mSwitchOn = true;//開關預設是開着的
    private int mMoveLength;//最大移動距離
    private float mLastX = ;//第一次按下的有效區域

    private Rect mDest = null;//繪制的目标區域大小
    private Rect mSrc = null;//截取源圖檔的大小
    private int mDeltX = ;//移動的偏移量
    private Paint mPaint = null;
    private OnChangeListener mListener = null;
    private boolean mFlag = false;

    public SwitchButton(Context context) {
        this(context, null);
        // TODO Auto-generated constructor stub
    }

    public SwitchButton(Context context, AttributeSet attrs) {
        this(context, attrs, );
        // TODO Auto-generated constructor stub
    }

    public SwitchButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
        init();
    }

    /**
     * 初始化相關資源
     */
    public void init() {
        mSwitchBottom = BitmapFactory.decodeResource(getResources(),
                R.drawable.switch_bottom);
        mSwitchThumb = BitmapFactory.decodeResource(getResources(),
                R.drawable.switch_btn_pressed);
        mSwitchFrame = BitmapFactory.decodeResource(getResources(),
                R.drawable.switch_frame);
        mSwitchMask = BitmapFactory.decodeResource(getResources(),
                R.drawable.switch_mask);
        setOnClickListener(this);
        setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                return false;
            }
        });

        mMoveLength = mSwitchBottom.getWidth() - mSwitchFrame.getWidth();
        mDest = new Rect(, , mSwitchFrame.getWidth(), mSwitchFrame.getHeight());
        mSrc = new Rect();
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setAlpha();
        mPaint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // TODO Auto-generated method stub
        setMeasuredDimension(mSwitchFrame.getWidth(), mSwitchFrame.getHeight());
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // TODO Auto-generated method stub
        super.onDraw(canvas);
        if (mDeltX >  || mDeltX ==  && mSwitchOn) {
            if(mSrc != null) {
                mSrc.set(mMoveLength - mDeltX, , mSwitchBottom.getWidth()
                    - mDeltX, mSwitchFrame.getHeight());
            }
        } else if(mDeltX <  || mDeltX ==  && !mSwitchOn){
            if(mSrc != null) {
                mSrc.set(-mDeltX, , mSwitchFrame.getWidth() - mDeltX,
                    mSwitchFrame.getHeight());
            }
        }

//這兒是離屏緩沖,自己感覺類似雙緩沖機制吧
        int count = canvas.saveLayer(new RectF(mDest), null, Canvas.MATRIX_SAVE_FLAG
                | Canvas.CLIP_SAVE_FLAG | Canvas.HAS_ALPHA_LAYER_SAVE_FLAG
                | Canvas.FULL_COLOR_LAYER_SAVE_FLAG
                | Canvas.CLIP_TO_LAYER_SAVE_FLAG);

        canvas.drawBitmap(mSwitchBottom, mSrc, mDest, null);
        canvas.drawBitmap(mSwitchThumb, mSrc, mDest, null);
        canvas.drawBitmap(mSwitchFrame, , , null);
        canvas.drawBitmap(mSwitchMask, , , mPaint);
        canvas.restoreToCount(count);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            mLastX = event.getX();
            break;
        case MotionEvent.ACTION_MOVE:
            mCurrentX = event.getX();
            mDeltX = (int) (mCurrentX - mLastX);
            // 如果開關開着向左滑動,或者開關關着向右滑動(這時候是不需要處理的)
            if ((mSwitchOn && mDeltX < ) || (!mSwitchOn && mDeltX > )) {
                mFlag = true;
                mDeltX = ;
            }

            if (Math.abs(mDeltX) > mMoveLength) {
                mDeltX = mDeltX >  ? mMoveLength : - mMoveLength;
            }
            invalidate();
            return true;
        case MotionEvent.ACTION_UP:
            if (Math.abs(mDeltX) >  && Math.abs(mDeltX) < mMoveLength / ) {
                mDeltX = ;
                invalidate();
                return true;
            } else if (Math.abs(mDeltX) > mMoveLength /  && Math.abs(mDeltX) <= mMoveLength) {
                mDeltX = mDeltX >  ? mMoveLength : -mMoveLength;
                mSwitchOn = !mSwitchOn;
                if(mListener != null) {
                    mListener.onChange(this, mSwitchOn);
                }
                invalidate();
                mDeltX = ;
                return true;
            } else if(mDeltX ==  && mFlag) {
                //這時候得到的是不需要進行處理的,因為已經move過了
                mDeltX = ;
                mFlag = false;
                return true;
            }
            return super.onTouchEvent(event);
        default:
            break;
        }
        invalidate();
        return super.onTouchEvent(event);
    }

    public void setOnChangeListener(OnChangeListener listener) {
        mListener = listener;
    }

    public interface OnChangeListener {
        public void onChange(SwitchButton sb, boolean state);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        mDeltX = mSwitchOn ? mMoveLength : -mMoveLength;
        mSwitchOn = !mSwitchOn;
        if(mListener != null) {
            mListener.onChange(this, mSwitchOn);
        }
        invalidate();
        mDeltX = ;
    }
}
           

2.測試是否好用

import com.example.switchbutton.SwitchButton.OnChangeListener;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SwitchButton sb = (SwitchButton) findViewById(R.id.wiperSwitch1);
        sb.setOnChangeListener(new OnChangeListener() {

            @Override
            public void onChange(SwitchButton sb, boolean state) {
                // TODO Auto-generated method stub
                Log.d("switchButton", state ? "開":"關");
                Toast.makeText(MainActivity.this, state ? "開":"關", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
           
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin" >

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <com.example.switchbutton.SwitchButton
        android:id="@+id/wiperSwitch1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="100dip" />
</LinearLayout>
           

本文轉載自csdn

原作者swust_chenpeng

原文位址:http://blog.csdn.net/swust_chenpeng/article/details/19967501

注:

白色圓點:switch_btn_pressed;

左白右紅的長條:switch_bottom;

無色長條:switch_frame;

黑色長條:switch_mask.