自定义View的初体验

Android自定义View的来源此处就不多提:

1.自定义View的基本步骤:

1.1创建一个类继承View,重写构造方法

    public SwitchButton(Context context) {
        this(context, null);
    }

    public SwitchButton(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SwitchButton(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public SwitchButton(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);	
    }
上面这种写法值得学习和参考

1.2编写values/attrs.xml,在其中编写styleable和item等标签元素(此步不为必须)

    <declare-styleable name="SwitchButton">
        <attr name="bg_on" format="reference" />
        <attr name="bg_off" format="reference" />
        <attr name="switch_on" format="reference" />
        <attr name="switch_off" format="reference" />
    </declare-styleable>

1.3布局文件中进行布局,如有自定义属性使用自定义属性(与1.2一样,自定义属性不一定必须)

1.4在构造函数中通过TypeArray ta = context.obtainStyleAttributes().获取自定义属性的值或进行其他初始化工作

1.5重写onMeasure()方法(不为必须---测量)

1.6重写onDraw()方法(绘制)

2.onMeasure

测量工作,不是自定义view的必须步骤,但其中有些细节得注意。
    @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);
        float scalex = 1.0f;
        float scaley = 1.0f;
        if (widthMode != MeasureSpec.UNSPECIFIED && widthSize < mWidth) {
            scalex = (float) widthSize / (float) mWidth;
        }
        if (heightMode != MeasureSpec.UNSPECIFIED && heightSize < mHeight) {
            scaley = (float) heightSize / (float) mHeight;
        }
        setMeasuredDimension(resolveSizeAndState((int) (mWidth * scalex), widthMeasureSpec, 0),
                resolveSizeAndState((int) (mHeight * scaley), heightMeasureSpec, 0));
    }

MeasureSpec.Mode有三种:1.UNSPECIFIED  对应着 wrapcontent
                                                             2.ATMOST  对应着matchparent
                                                             3.EXACTLY  对应着具体的长宽

3.onDraw

绘制工作,则是根据自己需要进行图形或者文字等绘制,不一一赘述。



最后附上一个简单的自定义Button

package com.example.zhoujiang.viewtest;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

/**
 * switchbutton简单的滑动BUTTON
 * Created by zhoujiang on 2017/5/3.
 */
public class SwitchButton extends View implements View.OnTouchListener {

    private Bitmap bgOn, bgOff, switchOn, switchOff;
    private int mWidth, mHeight;
    private boolean checked;
    private int nowX;
    private static final String TAG = SwitchButton.class.getSimpleName();
    private OnCheckedListener onCheckedListener;

    public SwitchButton(Context context) {
        this(context, null);
    }

    public SwitchButton(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SwitchButton(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public SwitchButton(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SwitchButton, defStyleAttr, defStyleRes);
        Drawable bg_On = typedArray.getDrawable(R.styleable.SwitchButton_bg_on);
        Drawable bg_Off = typedArray.getDrawable(R.styleable.SwitchButton_bg_off);
        Drawable switch_On = typedArray.getDrawable(R.styleable.SwitchButton_switch_on);
        Drawable switch_Off = typedArray.getDrawable(R.styleable.SwitchButton_switch_off);

        BitmapDrawable on = (BitmapDrawable) bg_On;
        BitmapDrawable off = (BitmapDrawable) bg_Off;
        BitmapDrawable son = (BitmapDrawable) switch_On;
        BitmapDrawable soff = (BitmapDrawable) switch_Off;

        bgOn = on.getBitmap();
        bgOff = off.getBitmap();
        switchOn = son.getBitmap();
        switchOff = soff.getBitmap();

        mWidth = bgOn.getWidth();
        mHeight = bgOn.getHeight();

        typedArray.recycle();

        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);
        float scalex = 1.0f;
        float scaley = 1.0f;
        if (widthMode != MeasureSpec.UNSPECIFIED && widthSize < mWidth) {
            scalex = (float) widthSize / (float) mWidth;
        }
        if (heightMode != MeasureSpec.UNSPECIFIED && heightSize < mHeight) {
            scaley = (float) heightSize / (float) mHeight;
        }
        setMeasuredDimension(resolveSizeAndState((int) (mWidth * scalex), widthMeasureSpec, 0),
                resolveSizeAndState((int) (mHeight * scaley), heightMeasureSpec, 0));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint paint = new Paint();
        Log.d(TAG, "-----" + checked);

        if (nowX < (bgOn.getWidth() - switchOn.getWidth()) / 2) {
            canvas.drawBitmap(bgOff, 0, 0, paint);
        } else {
            canvas.drawBitmap(bgOn, 0, 0, paint);
        }
        //防止划出
        if (nowX >= bgOn.getWidth() - switchOn.getWidth()) {
            nowX = bgOn.getWidth() - switchOn.getWidth();
        }

        if (nowX < (bgOn.getWidth() - switchOn.getWidth()) / 2) {
            canvas.drawBitmap(switchOff, nowX, 0, paint);
        } else {
            canvas.drawBitmap(switchOn, nowX, 0, paint);
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        Log.d(TAG, "---- " + v.getX() + ",------" + v.getY());
        int action = event.getAction();
        int eventX = (int) event.getX();
        Log.d(TAG, "------X=" + eventX);
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                nowX = eventX;
                break;
            case MotionEvent.ACTION_MOVE:
                nowX = eventX;
                break;
            case MotionEvent.ACTION_UP:
                //最后的状态还原
                if (eventX < (bgOn.getWidth() - switchOn.getWidth()) / 2) {
                    checked = false;
                    nowX = 0;
                } else {
                    checked = true;
                    nowX = bgOn.getWidth() - switchOn.getWidth();
                }
                //进行状态回调
                if (onCheckedListener != null) {
                    onCheckedListener.statedchange(SwitchButton.this, checked);
                }
                break;
        }
        invalidate();
        return true;
    }

    /**
     * 设置初始状态
     */
    public void setChecked(boolean checked) {
        if (checked) {
            nowX = bgOn.getWidth() - switchOn.getWidth();
        } else {
            nowX = 0;
        }
        invalidate();
    }

    /**
     * 设置监听
     */
    public void setOnCheckedListener(OnCheckedListener checkedListener) {
        onCheckedListener = checkedListener;
    }

    private interface OnCheckedListener {
        void statedchange(SwitchButton switchButton, boolean checked);
    }
}





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值