Android自定义View——滑动按钮

1.实现滑动按钮自定义View

滑动按钮
自定义 ToggleView继承View完整代码

public class ToggleView extends View {

    private Bitmap buttonBitmap;//按钮
    private Bitmap switchBitmap;//背景
    private Paint p;//定义画笔
    private boolean mState = false;//开关状态
    private float currentX;//当前位置
    private boolean isTouchMode = false;//触摸模式

    //代码创建控件
    public ToggleView(Context context) {
        super(context);
        init();
    }

    //xml文件,包括自定义属性
    public ToggleView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
        //自定义属性
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ToggleView);
        if (typedArray != null) {
            int switchBg = typedArray.getResourceId(R.styleable.ToggleView_switchBg,R.drawable.switch_background);
            int slideButton = typedArray.getResourceId(R.styleable.ToggleView_slideButton,R.drawable.slide_button);
            boolean state= typedArray.getBoolean(R.styleable.ToggleView_state,false);
            setSwitchBackground(switchBg);
            setSlideButton(slideButton);
            setSwitchState(state);
            typedArray.recycle();//资源回收
        }
    }

    //xml使用,指定了样式,走该构造方法
    public ToggleView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
         init();
    }

    private void init() {
        p = new Paint();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //设置图片原始的宽和高
        setMeasuredDimension(switchBitmap.getWidth(),switchBitmap.getHeight());
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //1.绘制背景(0,0)指定图片左上角坐标
        canvas.drawBitmap(switchBitmap,0,0, p);
        //2.绘制滑块
        if (isTouchMode){//down-move-move...时执行
            //根据触摸位置画滑块
            float newLeft = currentX - buttonBitmap.getWidth()/2.0f;//左移半个滑块的位置
            float maxLeft = switchBitmap.getWidth() - buttonBitmap.getWidth();
            //限定最左最右位置
            if (newLeft < 0) {
                newLeft = 0;
            }else if (newLeft > maxLeft){
                newLeft = maxLeft;
            }
            canvas.drawBitmap(buttonBitmap, newLeft, 0, p);
        }else {//up时执行
            if (mState) {//开的状态
                int newLeft = switchBitmap.getWidth() - buttonBitmap.getWidth();
                canvas.drawBitmap(buttonBitmap, newLeft, 0, p);
            } else {
                canvas.drawBitmap(buttonBitmap, 0, 0, p);
            }
        }
    }

    //重写触摸事件
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                isTouchMode = true;
                currentX = event.getX();
                break;
            case MotionEvent.ACTION_MOVE:
                currentX = event.getX();
                break;
            case MotionEvent.ACTION_UP:
                currentX = event.getX();
                float center = switchBitmap.getWidth()/2.0f;
                // 抬起位置与中间位置比较
                boolean nowstate=currentX > center;
                //状态变化了
                if (nowstate!=mState && listener!=null){
                    mState = nowstate;
                    listener.onClick(mState);//up时监听
                }
                isTouchMode = false;
                break;
        }
        invalidate();//重绘
        return true;
    }

    //设置开关背景
    public void setSwitchBackground(int switchBackground) {
        switchBitmap = BitmapFactory.decodeResource(getResources(), switchBackground);

    }

    //设置滑动开关按钮
    public void setSlideButton(int slideButton) {
        buttonBitmap = BitmapFactory.decodeResource(getResources(), slideButton);
    }

    //设置开关状态
    public void setSwitchState(boolean state) {
        mState = state;
    }

    /**
     * 设置监听接口
     */
    private OnStateChangeListener listener;

    public void setOnClickListenet(OnStateChangeListener listener){
        this.listener = listener;
    }

    public interface OnStateChangeListener{
        void onClick(boolean state);
    }
}

2.自定义属性

1.在values下新建attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ToggleView">
        <attr name="state" format="boolean" />
        <attr name="switchBg" format="reference" />
        <attr name="slideButton" format="reference" />
    </declare-styleable>
</resources>

2.布局文件添加命名空间

   xmlns:toggle="http://schemas.android.com/apk/res-auto"

3.ToggleView在布局中的设置

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:toggle="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.pfj.toggleview.ui.ToggleView
        android:id="@+id/toggleView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        toggle:state ="false"
        toggle:switchBg="@drawable/switch_background"
        toggle:slideButton="@drawable/slide_button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

3.MainActivity

public class MainActivity extends AppCompatActivity {

    private ToggleView toggleView;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toggleView = findViewById(R.id.toggleView);
        //状态监听
        toggleView.setOnClickListenet(new ToggleView.OnStateChangeListener() {
            @Override
            public void onClick(boolean state) {
                Toast.makeText(MainActivity.this,"状态变化:" + state,Toast.LENGTH_SHORT).show();
            }
        });
    }
}
发布了28 篇原创文章 · 获赞 1 · 访问量 529

猜你喜欢

转载自blog.csdn.net/qq_40575302/article/details/104523397