自定义滑动Button开关

Posted glj521

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自定义滑动Button开关相关的知识,希望对你有一定的参考价值。

自定义控件

package test.baway.com.mybutton.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by gateway on 2016/6/21.
 */
public class MyToggleButton extends View {
    private Bitmap bgPic;
    private Bitmap iconPic;
    private  float toggleLeft;
    private  float toggleMaxLeft;
    private boolean isOpen=false;
    private  boolean isHandsUp = false;
    private OnTogglelistener onToggleListener;
    public MyToggleButton(Context context) {
        super(context);
    }

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

    }

    private void init(AttributeSet attrs) {
        //1.获取命名空间
        String namespace = "http://schemas.android.com/apk/res-auto";
        //从自定义属性中获取我们设置的值
        int backgroundId = attrs.getAttributeResourceValue(namespace, "mybackground", -1);
        int iconId = attrs.getAttributeResourceValue(namespace, "myicon", -1);
        System.out.println("backgroundId---------"+backgroundId+"------iconId----------"+iconId);
        boolean toggleState = attrs.getAttributeBooleanValue(namespace, "mytoggle", false);
        if(backgroundId != -1 && iconId != -1){
            setBackGroundPic(backgroundId, iconId);
        }
        setState(toggleState);
    }

    public MyToggleButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    private void setState(boolean isOpen) {
        isHandsUp=true;
        if(isOpen){
            toggleLeft=toggleMaxLeft;
        }else{
            toggleLeft=0;
        }
    }

    /**
     * 设置滑动开关背景图
     * @param bgpic 背景图片
     * @param iconpic 滑动图片
     */
    public void setBackGroundPic(int bgpic,int iconpic){
        this.bgPic= BitmapFactory.decodeResource(getResources(),bgpic);
        this.iconPic=BitmapFactory.decodeResource(getResources(),iconpic);
        toggleMaxLeft=this.bgPic.getWidth()-this.iconPic.getWidth();
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(bgPic.getWidth(),bgPic.getHeight());
    }

    @Override
    protected void onDraw(Canvas canvas) {


        canvas.drawBitmap(bgPic,0,0,null);

        //不让滑出左边
        if(toggleLeft<0){
            toggleLeft=0;
        }

        //不如滑出右边
        if(toggleLeft>toggleMaxLeft){
            toggleLeft=toggleMaxLeft;
        }

        isOpen = toggleLeft>0;
        if(isHandsUp){
            if(onToggleListener!=null){
                onToggleListener.onToggle(isOpen);
            }
            isHandsUp=false;
        }
        canvas.drawBitmap(iconPic,toggleLeft,0,null);
        super.onDraw(canvas);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                toggleLeft=event.getX()-iconPic.getWidth()/2;
                break;
            case MotionEvent.ACTION_MOVE:
                toggleLeft=event.getX()-iconPic.getWidth()/2;
                break;
            case MotionEvent.ACTION_UP:
                isHandsUp=true;
                if(event.getX()>bgPic.getWidth()/2){
                    toggleLeft=toggleMaxLeft;
                }else{
                    toggleLeft=0;
                }

                break;


        }

        invalidate();
        return true;
    }

    public void setOnToggleListener(OnTogglelistener onToggleListener){
        this.onToggleListener=onToggleListener;
    }
    public interface OnTogglelistener{
        void onToggle(boolean isOpen);
    }
}

方式一:

//通过set的方式设置背景和滑动按钮

布局中

 <test.baway.com.mybutton.view.MyToggleButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btn" />



activity中

  MyToggleButton btn = (MyToggleButton) findViewById(R.id.btn);
//通过set的方式设置背景和滑动按钮 btn.setBackGroundPic(R.mipmap.slide_background2,R.mipmap.slide_icon2); btn.setOnToggleListener(
new MyToggleButton.OnTogglelistener() { @Override public void onToggle(boolean isOpen) { if(isOpen){ Toast.makeText(MainActivity.this,"打开",Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(MainActivity.this,"关闭",Toast.LENGTH_SHORT).show(); } } });

方式二:

//通过自定义属性的方式设置背景和滑动按钮

values中创建attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyToggleButton">
        <attr name="mybackground" format="reference"></attr>
        <attr name="myicon" format="reference"></attr>
        <attr name="mytoggle" format="boolean"></attr>
    </declare-styleable>
</resources>

布局中

 

添加命名空间

AS中:xmlns:app="http://schemas.android.com/apk/res-auto"(eclipse中把res-auto改成包名)
 <test.baway.com.mybutton.view.MyToggleButton
        app:mybackground="@mipmap/slide_background"
        app:myicon="@mipmap/slide_icon"
        app:mytoggle="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btn" />

activity中

  MyToggleButton btn = (MyToggleButton) findViewById(R.id.btn);
       

        btn.setOnToggleListener(new MyToggleButton.OnTogglelistener() {
            @Override
            public void onToggle(boolean isOpen) {
                if(isOpen){
                    Toast.makeText(MainActivity.this,"打开",Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(MainActivity.this,"关闭",Toast.LENGTH_SHORT).show();
                }
            }
        });

 

以上是关于自定义滑动Button开关的主要内容,如果未能解决你的问题,请参考以下文章

如何在 VSCode 中添加自定义 emmet 片段?

Android中的自定义控件

使用删除与隐藏时未调用自定义动画

在代码片段中包含类型转换

WPF自定义Button控件

为片段制作自定义列表视图?