自定义View之WiperSwitch改进版

近日使用了一个滑动开关,使用的是xiaanming的WiperSwitch,地址在
http://blog.csdn.net/xiaanming/article/details/8842453
确实是个好东西,很容易就移植到app中,果然是没有版本不兼容问题。
可是在使用过程中,发现有些小问题,然后进行了改进。改进有如下几点:

1,支持控件的缩放;
2,解决有时开关会卡在中间的问题;
3,更换了图片;
4,解决滑动冲突问题;
5,onDraw 中不new;

先上个改进后的效果图:
这里写图片描述

下面分别对改进点进行说明:

1、支持控件的缩放

就是重写了onMeasure,根据设定的宽高值进行缩放。缩放时,为了美观,保持了view的宽高的比例;
设置缩放上下限:不能太大、太小,都没有意义,此处,我是限定上下限为 1/3 – 3倍;

2、解决有时开关会卡在中间的问题

运行时会遇到中间的滑动按钮卡在中间的情况,后来上网一顿查找,才知道是触摸事件onTouch()的处理中,有一种动作没有处理到,是MotionEvent.ACTION_CANCEL:
当保持按下操作,并从滑动开关转移到外层控件时,会触发MotionEvent.ACTION_CANCEL。
中onTouch()中添加上,并与MotionEvent.ACTION_UP做同样的处理,ok。

3、更换了图片

更换图片有些地方需要注意:
滑块的高度与背景图片的高度保持一致,滑块外缘是透明部分,通过透明部分来衬托出外边缘。
另外,说句题外话,做安卓开发,学习点PhotoShop也挺不错的。

4、解决滑动冲突问题

我在实际项目使用中,遇到将滑块滑动到中间部分时,突然跳转到另一头的情况。通过跟踪信息,发现竟然执行了MotionEvent.ACTION_CANCEL,原来是滑动事件被上层的布局给抢走了(我在外层使用了一个侧滑菜单,从而出现了滑动冲突)。
解决方法:
在ACTION_DOWN时禁止父ViewGroup的滑动监听:

getParent().requestDisallowInterceptTouchEvent(true);

在ACTION_CANCEL与ACTION_UP时恢复父ViewGroup的滑动监听:

getParent().requestDisallowInterceptTouchEvent(false);

5、onDraw 中不new

根据Lint的提示,View 的 onDraw() 方法会被频繁的调用,因此不建议在onDraw()函数体内进行对象分配。如果在其中有需要用到的对象,就把这些对象的分配放在别处。

6、下面是具体实现

package com.customview.view;

import com.customview.LogUtil;
import com.customview.R;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

/**
 * 
 * @author xiaanming,lintax
 *
 */
public class WiperSwitch extends View implements OnTouchListener{
    private Bitmap bg_on, bg_off, slipper_btn;
    /**
     * 按下时的x和当前的x
     */
    private float downX=0, nowX=0;

    /**
     * 记录用户是否在滑动
     */
    private boolean onSlip = false;

    /**
     * 当前的状态
     */
    private boolean nowStatus = false;

    /**
     * 监听接口
     */
    private OnChangedListener listener;

    Paint paint = null;//画笔
    float x = 0;//滑动块的x位置

    public WiperSwitch(Context context) {
        super(context);
        init();
    }

    public WiperSwitch(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public void init(){     
        LogUtil.logWithMethod(new Exception(),"init");

        //载入图片资源 
        bg_on = BitmapFactory.decodeResource(getResources(), R.drawable.switch_open);
        bg_off = BitmapFactory.decodeResource(getResources(),  R.drawable.switch_close);
        slipper_btn = BitmapFactory.decodeResource(getResources(),  R.drawable.switch_btn);

        x = 0;
        paint = new Paint();
        setOnTouchListener(this);
    }

    @Override  
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)  
    {  
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);  
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);  
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);  
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);  
        int width;  
        int height ;  

        boolean flagExactly=false;
        float viewWidth = (float)bg_on.getWidth();
        float viewHeight = (float)bg_on.getHeight();

        if (widthMode == MeasureSpec.EXACTLY)  
        {  
            width = widthSize;  
            flagExactly = true;
        } else  
        {              
            width = (int) (viewWidth ); 
        }  

        if (heightMode == MeasureSpec.EXACTLY)  
        {  
            height = heightSize;  
            flagExactly = true;
        } else  
        {          
            height = (int) ( viewHeight );   
        }  

        //如果是指定大小,且宽高值确实不一致了,要重新调整图片的大小
        if( flagExactly && ( (width!=viewWidth) || (height!=viewHeight) )){
            //限制调整的范围:最大3倍,比例需要保持(要调比例,换原始图片)
            //按比例,取小值
            float ratio = Math.min(width/viewWidth, height/viewHeight);
            if(ratio > 3){
                ratio = 3;
            } else if(ratio < 1/3){
                ratio = 1/3;
            }
            width=(int)(viewWidth*ratio);
            height=(int)(viewHeight*ratio);
            LogUtil.logWithMethod(new Exception(),"after change: width="+width+" height="+height);

            bg_on = Bitmap.createScaledBitmap(bg_on, width, height, false);
            bg_off = Bitmap.createScaledBitmap(bg_off, width, height, false);
            slipper_btn = Bitmap.createScaledBitmap(slipper_btn, height, height, false);

        }

        setMeasuredDimension(width, height);  
    }  


    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        x = 0;

        if(isInEditMode()){
            return;
        }

        //根据nowStatus设置背景,开或者关状态        
        if(nowStatus){
            canvas.drawBitmap(bg_on, 0, 0, paint);          
        }else{
            canvas.drawBitmap(bg_off, 0, 0, paint);         
        }

        if (onSlip) {//是否是在滑动状态,
            if(nowX >= bg_on.getWidth())//是否划出指定范围,不能让滑块跑到外头,必须做这个判断  
                x = bg_on.getWidth() - slipper_btn.getWidth()/2;//减去滑块1/2的长度  
            else
                x = nowX - slipper_btn.getWidth()/2;
        }else {
            if(nowStatus){//根据当前的状态设置滑块的x值,若不在滑动状态,非左即右!
                x = bg_on.getWidth() - slipper_btn.getWidth();
            }else{
                x = 0;
            }
        }

        //对滑块滑动进行异常处理,不能让滑块出界
        if (x < 0 ){
            x = 0;
        }
        else if(x > bg_on.getWidth() - slipper_btn.getWidth()){
            x = bg_on.getWidth() - slipper_btn.getWidth();
        }

        //画出滑块 
        canvas.drawBitmap(slipper_btn, x , 0, paint);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch(event.getAction()){
        case MotionEvent.ACTION_DOWN:{
            LogUtil.logWithMethod(new Exception(), "ACTION_DOWN");
            if (event.getX() > bg_off.getWidth() || event.getY() > bg_off.getHeight()){
                return false;
            }else{
                onSlip = true;
                downX = event.getX();
                nowX = downX;
            }
            //LogUtil.logWithMethod(new Exception(),"ACTION_DOWN: nowX="+nowX);

            getParent().requestDisallowInterceptTouchEvent(true);//禁止父ViewGroup的滑动监听

            break;
        }
        case MotionEvent.ACTION_MOVE:{
            nowX = event.getX();
            if(event.getX() >= (bg_on.getWidth()/2)){
                nowStatus = true;
            }else{
                nowStatus = false;
            }
            break;
        }
        case MotionEvent.ACTION_CANCEL:
            //LogUtil.logWithMethod(new Exception(),"ACTION_CANCEL:");
        case MotionEvent.ACTION_UP:{

            onSlip = false;
            if(event.getX() >= (bg_on.getWidth()/2)){
                LogUtil.logWithMethod(new Exception(), "ACTION_UP: choseed");
                nowStatus = true;
                nowX = bg_on.getWidth() - slipper_btn.getWidth();
            }else{
                LogUtil.logWithMethod(new Exception(), "ACTION_UP: un choseed");
                nowStatus = false;
                nowX = 0;
            }
            //LogUtil.logWithMethod(new Exception(),"ACTION_UP: nowX="+nowX);
            if(listener != null){
                listener.OnChanged(WiperSwitch.this, nowStatus);
            }

            getParent().requestDisallowInterceptTouchEvent(false);//使能父ViewGroup的滑动监听

            break;
        }
        }
        //刷新界面 
        invalidate();
        return true;
    }


    /**
     * 为WiperSwitch设置一个监听,供外部调用的方法 
     * @param listener
     */
    public void setOnChangedListener(OnChangedListener listener){
        this.listener = listener;
    }


    /**
     * 设置滑动开关的初始状态,供外部调用 
     * @param checked
     */
    public void setChecked(boolean checked){
        if(checked){
            nowX = bg_off.getWidth();
        }else{
            nowX = 0;
        }
        nowStatus = checked;
        invalidate();

    }


    /**
     * 回调接口 
     * @author len
     *
     */
    public interface OnChangedListener {
        public void OnChanged(WiperSwitch wiperSwitch, boolean checkState);
    }

}

7、调用View的布局xml

布局中就只是存放了3个View,演示调用方法:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:custom="http://schemas.android.com/apk/res/com.customview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >


    <com.customview.view.WiperSwitch
         android:id="@+id/switch1"            
         android:layout_width="80dp"
         android:layout_height="40dp"
         android:layout_marginTop="10dp"
         android:layout_gravity="center_horizontal"
         />

    <com.customview.view.WiperSwitch
         android:id="@+id/switch2"
         android:layout_width="120dp"
         android:layout_height="40dp"
         android:layout_marginTop="10dp"
         android:layout_gravity="center_horizontal"
         />

    <com.customview.view.WiperSwitch
         android:id="@+id/switch3"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_marginTop="10dp"
         android:layout_gravity="center_horizontal"          
         />

</LinearLayout>

8、主Activity

主Activity中访问滑动开关,可以设置初始状态:

switch1.setChecked(true);

以及监控开关的状态变化:

switch1.setOnChangedListener(new OnChangedListener() {

具体实现如下:

package com.customview;

import android.os.Bundle;
import android.view.WindowManager;
import com.customview.view.WiperSwitch;
import com.customview.view.WiperSwitch.OnChangedListener;
import android.app.Activity;

public class MainActivity extends Activity
{
    WiperSwitch switch1;
    WiperSwitch switch2;
    WiperSwitch switch3;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState); 
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);//去掉信息栏
        setContentView(R.layout.activity_main);

        LogUtil.logWithMethod(new Exception());

        switch1 = (WiperSwitch) findViewById(R.id.switch1);
        switch2 = (WiperSwitch) findViewById(R.id.switch2);
        switch3 = (WiperSwitch) findViewById(R.id.switch3);

        switch1.setChecked(true);
        switch2.setChecked(true);
        switch3.setChecked(false);

        switch1.setOnChangedListener(new OnChangedListener() {          
            @Override
            public void OnChanged(WiperSwitch wiperSwitch, boolean checkState) {
                // TODO Auto-generated method stub
                LogUtil.logWithMethod(new Exception(),"switch1 checkState="+checkState);
            }
        });

        switch2.setOnChangedListener(new OnChangedListener() {          
            @Override
            public void OnChanged(WiperSwitch wiperSwitch, boolean checkState) {
                // TODO Auto-generated method stub
                LogUtil.logWithMethod(new Exception(),"switch2 checkState="+checkState);
            }
        });

        switch3.setOnChangedListener(new OnChangedListener() {          
            @Override
            public void OnChanged(WiperSwitch wiperSwitch, boolean checkState) {
                // TODO Auto-generated method stub
                LogUtil.logWithMethod(new Exception(),"switch3 checkState="+checkState);
            }
        });
    }    
}

9、源代码地址:

http://download.csdn.net/detail/lintax/9674388

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章