首页 > 代码库 > 自定义带滑动属性的Switch

自定义带滑动属性的Switch

1. 效果图

技术分享

2. SlidingSwitch.java文件内容:

<pre name="code" class="java">package com.jun.widget;


import com.jun.slidingswitch.R;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

/**
 * 
 * slidingSwitch.setCheck(true);
 * slidingSwitch.SetOnChangedListener(new OnChangedListener()
 * {
 *     @Override
 *     public void OnChanged(boolean CheckState)
 *     {
 *         //处理slidingSwitch开关事件
 *     }
 * });
**/

public class SlidingSwitch extends View implements OnTouchListener
{
    private boolean NowChoose = false;// 记录当前按钮是否打开,true为打开,flase为关闭
    private boolean isChecked;
    private boolean OnSliding = false;// 记录用户是否在滑动的变量
    private float DownX, NowX;// 按下时的x,当前的x
    private Rect Btn_On, Btn_Off;// 打开和关闭状态下,游标的Rect
    private boolean isChgLsnOn = false;
    private OnChangedListener ChgLsn;
    private Bitmap bg_on, bg_off, sliding_switch;
    public SlidingSwitch(Context context)
    {
        super(context);
        init();
    }
    public SlidingSwitch(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        init();
    }
    public SlidingSwitch(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        init();
    }
    private void init()
    {// 初始化
        bg_on = BitmapFactory.decodeResource(getResources(), R.drawable.slip_left);
        bg_off = BitmapFactory.decodeResource(getResources(), R.drawable.slip_right);
        sliding_switch = BitmapFactory.decodeResource(getResources(), R.drawable.slip_ball);
        Btn_On = new Rect(0, 0, sliding_switch.getWidth(), sliding_switch.getHeight());
        Btn_Off = new Rect(bg_off.getWidth() - sliding_switch.getWidth(), 0, bg_off.getWidth(),
                sliding_switch.getHeight());
        setOnTouchListener(this);// 设置监听器,也可以直接复写OnTouchEvent
    }
    @SuppressLint("DrawAllocation")
    @Override
    protected void onDraw(Canvas canvas)
    {// 绘图函数
        super.onDraw(canvas);
        Matrix matrix = new Matrix();
        Paint paint = new Paint();
        float x;
        if (NowX < (bg_on.getWidth() / 2))// 滑动到前半段与后半段的背景不同,在此做判断
        {
            x = NowX - sliding_switch.getWidth() / 2;
            canvas.drawBitmap(bg_off, matrix, paint);// 画出关闭时的背景
        }
        else
        {
            x = bg_on.getWidth() - sliding_switch.getWidth() / 2;
            canvas.drawBitmap(bg_on, matrix, paint);// 画出打开时的背景
        }
        if (OnSliding)// 是否是在滑动状态,
        {
            if (NowX >= bg_on.getWidth())// 是否划出指定范围,不能让游标跑到外头,必须做这个判断
                x = bg_on.getWidth() - sliding_switch.getWidth() / 2;// 减去游标1/2的长度...
            else if (NowX < 0)
            {
                x = 0;
            }
            else
            {
                x = NowX - sliding_switch.getWidth() / 2;
            }
        }
        else
        {// 非滑动状态
            if (NowChoose)// 根据现在的开关状态设置画游标的位置
            {
                x = Btn_Off.left;
                canvas.drawBitmap(bg_on, matrix, paint);// 初始状态为true时应该画出打开状态图片
            }
            else
                x = Btn_On.left;
        }
        if (isChecked)
        {
            canvas.drawBitmap(bg_on, matrix, paint);
            x = Btn_Off.left;
            isChecked = !isChecked;
        }
        if (x < 0)// 对游标位置进行异常判断...
            x = 0;
        else if (x > bg_on.getWidth() - sliding_switch.getWidth())
            x = bg_on.getWidth() - sliding_switch.getWidth();
        canvas.drawBitmap(sliding_switch, x, 0, paint);// 画出游标.
    }
    
    @Override
    public boolean onTouch(View v, MotionEvent event)
    {
        switch (event.getAction())
        // 根据动作来执行代码
        {
            case MotionEvent.ACTION_MOVE:// 滑动
                NowX = event.getX();
                break;
            case MotionEvent.ACTION_DOWN:// 按下
                if (event.getX() > bg_on.getWidth() || event.getY() > bg_on.getHeight())
                    return false;
                OnSliding = true;
                DownX = event.getX();
                NowX = DownX;
                break;
            case MotionEvent.ACTION_CANCEL: // 移到控件外部
            	OnSliding = false;
                boolean choose = NowChoose;
                if (NowX >= (bg_on.getWidth() / 2))
                {
                    NowX = bg_on.getWidth() - sliding_switch.getWidth() / 2;
                    NowChoose = true;
                }
                else
                {
                    NowX = NowX - sliding_switch.getWidth() / 2;
                    NowChoose = false;
                }
                if (isChgLsnOn && (choose != NowChoose)) // 如果设置了监听器,就调用其方法..
                    ChgLsn.OnChanged(NowChoose);
                break;
            case MotionEvent.ACTION_UP:// 松开
            	OnSliding = false;
                boolean LastChoose = NowChoose;
                if (event.getX() >= (bg_on.getWidth() / 2))
                {
                    NowX = bg_on.getWidth() - sliding_switch.getWidth() / 2;
                    NowChoose = true;
                }
                else
                {
                    NowX = NowX - sliding_switch.getWidth() / 2;
                    NowChoose = false;
                }
                if (isChgLsnOn && (LastChoose != NowChoose)) // 如果设置了监听器,就调用其方法..
                    ChgLsn.OnChanged(NowChoose);
                break;
            default:
        }
        invalidate();// 重画控件
        return true;
    }
    
    public void SetOnChangedListener(OnChangedListener l)
    {
        // 设置监听器,当状态修改的时候
        isChgLsnOn = true;
        ChgLsn = l;
    }
    
    public interface OnChangedListener
    {
        abstract void OnChanged(boolean CheckState);
    }
    
    public void setCheck(boolean isChecked)
    {
        this.isChecked = isChecked;
        NowChoose = isChecked;
    }
}




2. activity_main.xml布局内容:


<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.jun.slidingswitch.MainActivity" >

    <com.jun.widget.SlidingSwitch
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</RelativeLayout>

3. MainActivity.java文件内容:


package com.jun.slidingswitch;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends ActionBarActivity {

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

	@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;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}


5.demo(百度云网盘)

http://pan.baidu.com/s/1dDpgqdV



自定义带滑动属性的Switch