Android 开发之自定义滑动开关

滑动开关--------  
自定义控件步骤:    
测量:onMeasure设置自己显示在屏幕上的宽高    
布局:onLayout 设置自己显示在屏幕上的位置(只有在自定义ViewGroup中才用到)    
绘制:onDraw 控制显示在屏幕上的样子(自定义viewgroup时不需要这个)

View和ViewGroup的区别  
1.他们都需要进行测量操作    
2.ViewGroup主要是控制子view如何摆放,所以必须实现onLayout    
 View没有子view,所以不需要onLayout方法,但是必须实现onDraw

效果图:

Android 开发之自定义滑动开关_第1张图片

下面直接贴demo代码

布局文件

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context=".MainActivity">

    <com.zaizai.slideswitch.MyToggleButton
        android:id="@+id/my_toggle_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />
</RelativeLayout>

MytoggleButton.java代码

package com.zaizai.slideswitch;

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.OnClickListener;

public class MyToggleButton extends View {

    private ToggleState toggleState = ToggleState.Open;
    private Bitmap slideBg;
    private Bitmap switchBg;
    private boolean isSliding = false;

    private int currentX;

    /**
     * view在java代码中动态创建,需要重写该方法
     *
     * @param context
     */
    public MyToggleButton(Context context) {
        super(context);
    }

    /**
     * view只是在布局文件中使用,只需要重写该方法
     *
     * @param context
     * @param attrs
     */
    public MyToggleButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    /**
     * 定义view 在屏幕显示的高度
     *
     * @param widthMeasureSpec
     * @param heightMeasureSpec
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        /*将开关背景的宽高设置进去*/
        setMeasuredDimension(switchBg.getWidth(), switchBg.getHeight());
    }

    /**
     * 绘制自己在屏幕显示时的样子
     *
     * @param canvas
     */
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //1、绘制背景图片
        canvas.drawBitmap(switchBg, 0, 0, null);
        //2、绘制滑动片图片
        if (isSliding) {
            int let = currentX - slideBg.getWidth() / 2;
            if (let < 0) {
                let = 0;
            }
            if (let > (switchBg.getWidth() - slideBg.getWidth())) {
                let = switchBg.getWidth() - slideBg.getWidth();
            }
            canvas.drawBitmap(slideBg, let, 0, null);
        } else {
            if (toggleState == ToggleState.Open) {
                canvas.drawBitmap(slideBg, switchBg.getWidth() - slideBg.getWidth(), 0, null);
            } else {
                canvas.drawBitmap(slideBg, 0, 0, null);
            }
        }


    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        currentX = (int) event.getX();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN: {
                isSliding = true;
                break;
            }
            case MotionEvent.ACTION_MOVE: {
                break;
            }
            case MotionEvent.ACTION_UP: {
                isSliding = false;
                int centerX = switchBg.getWidth() / 2;
                if (currentX > centerX) {
                    if (toggleState != ToggleState.Open) {
                        toggleState = ToggleState.Open;
                        if (listener != null) {
                            listener.onTaggleStateChange(toggleState);
                        }
                    }
                } else {
                    if (toggleState != ToggleState.close) {
                        toggleState = ToggleState.close;
                        if (listener != null) {
                            listener.onTaggleStateChange(toggleState);
                        }
                    }
                }
              
                break;
            }
            default: {
                break;
            }
        }
        //调用该方法去通知系统调用onDraw()方法
        invalidate();
        return true;
    }

    private OnToggleStateChangeListener listener;

    public void setOnToggleStateChangeListener(OnToggleStateChangeListener listener) {
        this.listener = listener;
    }

    public interface OnToggleStateChangeListener {
        void onTaggleStateChange(ToggleState state);
    }

    /**
     * 设置滑动块的背景图片
     *
     * @param slideButtonBackGround
     */
    public void setSlideBackGroundResource(int slideButtonBackGround) {
        /*将图片id转换为位图*/
        slideBg = BitmapFactory.decodeResource(getResources(), slideButtonBackGround);

    }

    /**
     * 设置滑动开关的背景图片
     *
     * @param switchBackGround
     */
    public void setSwitchBackGraoundResource(int switchBackGround) {
        switchBg = BitmapFactory.decodeResource(getResources(), switchBackGround);
    }

    public void setToggleState(ToggleState toggleState) {
        this.toggleState = toggleState;
    }

    public enum ToggleState {
        Open, close;
    }
}
主mainActivity代码
package com.zaizai.slideswitch;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private MyToggleButton toggleButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toggleButton = (MyToggleButton) findViewById(R.id.my_toggle_btn);
        toggleButton.setSlideBackGroundResource(R.drawable.slide_button);
        toggleButton.setSwitchBackGraoundResource(R.drawable.switch_background);
        toggleButton.setToggleState(MyToggleButton.ToggleState.Open);
        toggleButton.setOnToggleStateChangeListener(new MyToggleButton.OnToggleStateChangeListener() {
            @Override
            public void onTaggleStateChange(MyToggleButton.ToggleState state) {

                Toast.makeText(getApplicationContext(), state == MyToggleButton.ToggleState.Open ? "开启" : "关闭", 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.activity_main, menu);
        return true;
    }*/
}

你可能感兴趣的:(android,ToggleButton)