美文网首页
自定义View的简单流程

自定义View的简单流程

作者: 李俊的博客 | 来源:发表于2016-07-26 20:39 被阅读76次

自定义View的步骤

1、自定义属性

1)分析自定义的View中需要哪些的自定义属性,在res/values/attrs.xml中声明自定义属性,如下所示:
res/values/attrs.xml

<resources>
    // CustomTitleView的自定义属性
    <attr name="customTitleText" format="string"/>
    <attr name="customTitleTextSize" format="dimension"/>
    <attr name="customTitleTextColor" format="color"/>
    <declare-styleable name="CustomTitleView">
        <attr name="customTitleText"/>
        <attr name="customTitleTextSize"/>
        <attr name="customTitleTextColor"/>
    </declare-styleable>
</resources>

2)在自定义的View的构造方法中获取自定义属性。

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

public CustomTitleView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

public CustomTitleView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);

    // 获取自定义样式属性
    TypedArray a = context.getTheme()
            .obtainStyledAttributes(attrs, R.styleable.CustomTitleView, defStyleAttr, 0);
    int n = a.getIndexCount();
    for (int i = 0; i < n; i++) {
        int attr = a.getIndex(i);
        switch (attr) {
            case R.styleable.CustomTitleView_customTitleText:
                mCustomTitleText = a.getString(attr);
                break;
            // 设置默认字体大小为16sp,TypeValue也可以把sp转化为px。
            case R.styleable.CustomTitleView_customTitleTextSize:
                mCustomTitleTextSize = a.getDimensionPixelSize(attr,
                        (int) TypedValue.applyDimension(
                                TypedValue.COMPLEX_UNIT_SP,
                                16,
                                getResources().getDisplayMetrics()));
                break;
            // 设置默认字体颜色为黑色
            case R.styleable.CustomTitleView_customTitleTextColor:
                mCustomTitleTextColor = a.getColor(attr, Color.BLACK);
                break;
        }
    }
    // 最后记得释放资源
    a.recycle();
}

在obtainStyledAttributes()中有四个参数,最后两个参数分别是defStyleAttr和defStyleRes。defStyleAttr指定的是在Theme style中定义的一个attr;而defStyleRes是自己指定的一个style,当且仅当defStyleAttr为0或者在Theme中找不到defStyleAttr指定的属性时才会生效。属性指定的优先级优大概是:xml>style>defStyleAttr>defStyleRes>Theme指定,当defStyleAttr为0时,就跳过defStyleAttr指定的reference,所以一般用0就能满足一些基本开发。
3)在XML布局文件中使用自定义View时设置自定义属性。

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.jun.androidexample.customview.CustomTitleView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:padding="12dp"
        custom:customTitleText="8745"
        custom:customTitleTextColor="#ff0000"
        custom:customTitleTextSize="30sp"/>
</RelativeLayout>
2、onMesure()
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    
    /**
     * 计算View的宽度
     */
    // 获取widthMeasureSpec的Mode和Size
    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    // View的最终宽度
    int width;
    // 如果MeasureSpec的Mode是EXACTLY则最终的值直接等于MeasureSpec的Size
    if (widthMode == MeasureSpec.EXACTLY) {
        width = widthSize;
    } else { // 如果MeasureSpec的Mode是AT_MOST或UNSPECIFIED则需要测量其实际的值
        // 实际测量的值
        int desired = ...;
        // 如果MeasureSpec的Mode是AT_MOST则最大不能超过MeasureSpec的Size
        if (widthMode == MeasureSpec.AT_MOST) {
            // 所以最终的值等于MeasureSpec的Size和实际测量的值中的小的
            width = Math.min(widthSize, desired);
        } else {
            // 如果MeasureSpec的Mode是UNSPECIFIED则最终的值直接等于实际测量的值
            width = desired;
        }
    }

    /**
     * 计算View的高度
     */
    // 获取heightMeasureSpec的Mode和Size
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);
    // View的最终高度
    int height;
    // 如果MeasureSpec的Mode是EXACTLY则最终的值直接等于MeasureSpec的Size
    if (heightMode == MeasureSpec.EXACTLY) {
        height = heightSize;
    } else { // 如果MeasureSpec的Mode是AT_MOST或UNSPECIFIED则需要测量其实际的值
        // 实际测量的值
        int desired = ...;
        // 如果MeasureSpec的Mode是AT_MOST则最大不能超过MeasureSpec的Size
        if (heightMode == MeasureSpec.AT_MOST) {
            // 所以最终的值等于MeasureSpec的Size和实际测量的值中的小的
            height = Math.min(heightSize, desired);
        } else {
            // 如果MeasureSpec的Mode是UNSPECIFIED则最终的值直接等于实际测量的值
            height = desired;
        }
    }

    // 设置测量的宽度和高度
    setMeasuredDimension(width, height);
}

int型的widthMeasureSpec和heightMeasureSpec,在MeasureSpce中(在java中int型由4个字节(32bit)组成)前2位表示mode,后30位表示size。MeasureSpec的mode一共有三种类型:
1)EXACTLY:一般是android:layout_width或android:layout_height属性设置了明确的值或者是match_parent时,表示子View的大小就是MeasureSpec的size。
2)AT_MOST:一般是android:layout_width或android:layout_height属性设置成wrap_content,表示子View最大不超过MeasureSpec的size。
3)UNSPECIFIED:表示子View的大小不受限制也就是等于它实际测量的大小。

3、onDraw()
@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    // 使用Canvas绘制View
    ...
}

根据实际的需求绘制View的形状。

4、onTouchEvent()
@Override
public boolean onTouchEvent(MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            ...
            break;
        case MotionEvent.ACTION_MOVE:
            ...
            break;
        case MotionEvent.ACTION_UP:
            ...
            break;
    }
    return true;
}

如果自定义的View需要自己处理特定的触摸事件,就需要重写onTouchEvent()。

示例:点击随机改变数字

效果
效果图
实现

res/values/attrs.xml

<resources>
    // CustomTitleView的自定义属性
    <attr name="customTitleText" format="string"/>
    <attr name="customTitleTextSize" format="dimension"/>
    <attr name="customTitleTextColor" format="color"/>
    <declare-styleable name="CustomTitleView">
        <attr name="customTitleText"/>
        <attr name="customTitleTextSize"/>
        <attr name="customTitleTextColor"/>
    </declare-styleable>
</resources>

CustomTitleView.java

/**
 * 自定义View
 */
public class CustomTitleView extends View {

    // 声明自定义属性
    private String mCustomTitleText;
    private float mCustomTitleTextSize;
    private int mCustomTitleTextColor;

    private Paint mPaint;
    private Rect mBound;

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

    public CustomTitleView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomTitleView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        // 获取自定义样式属性
        TypedArray a = context.getTheme()
                .obtainStyledAttributes(attrs, R.styleable.CustomTitleView, defStyleAttr, 0);
        int n = a.getIndexCount();
        for (int i = 0; i < n; i++) {
            int attr = a.getIndex(i);
            switch (attr) {
                case R.styleable.CustomTitleView_customTitleText:
                    mCustomTitleText = a.getString(attr);
                    break;
                // 设置默认字体大小为16sp,TypeValue也可以把sp转化为px
                case R.styleable.CustomTitleView_customTitleTextSize:
                    mCustomTitleTextSize = a.getDimensionPixelSize(attr,
                            (int) TypedValue.applyDimension(
                                    TypedValue.COMPLEX_UNIT_SP,
                                    16,
                                    getResources().getDisplayMetrics()));
                    break;
                // 设置默认字体颜色为黑色
                case R.styleable.CustomTitleView_customTitleTextColor:
                    mCustomTitleTextColor = a.getColor(attr, Color.BLACK);
                    break;
            }
        }
        // 最后记得释放资源
        a.recycle();

        // 初始化Paint和Rect
        mPaint = new Paint();
        mBound = new Rect();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        // 获取MeasureSpec的Mode和Size
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        // 声明最终的值
        int width;
        int height;

        // 如果MeasureSpec的Mode是EXACTLY则最终的值直接等于MeasureSpec的Size
        if (widthMode == MeasureSpec.EXACTLY) {
            width = widthSize;
        } else { // 如果MeasureSpec的Mode是AT_MOST或UNSPECIFIED则需要测量其实际的值
            mPaint.setTextSize(mCustomTitleTextSize);
            mPaint.getTextBounds(mCustomTitleText, 0, mCustomTitleText.length(), mBound);
            float textWidth = mBound.width();
            int desired = (int) (getPaddingLeft() + textWidth + getPaddingRight());

            if (widthMode == MeasureSpec.AT_MOST) {
                // 如果MeasureSpec的Mode是AT_MOST则最大不能超过MeasureSpec的Size
                // 所以最终的值等于MeasureSpec的Size和实际测量的值中的小的
                width = Math.min(widthSize, desired);
            } else {
                // 如果MeasureSpec的Mode是UNSPECIFIED则最终的值直接等于实际测量的值
                width = desired;
            }
        }

        // 如果MeasureSpec的Mode是EXACTLY则最终的值直接等于MeasureSpec的Size
        if (heightMode == MeasureSpec.EXACTLY) {
            height = heightSize;
        } else { // 如果MeasureSpec的Mode是AT_MOST或UNSPECIFIED则需要测量其实际的值
            mPaint.setTextSize(mCustomTitleTextSize);
            mPaint.getTextBounds(mCustomTitleText, 0, mCustomTitleText.length(), mBound);
            float textHeight = mBound.height();
            int desired = (int) (getPaddingTop() + textHeight + getPaddingBottom());

            if (heightMode == MeasureSpec.AT_MOST) {
                // 如果MeasureSpec的Mode是AT_MOST则最大不能超过MeasureSpec的Size
                // 所以最终的值等于MeasureSpec的Size和实际测量的值中的小的
                height = Math.min(heightSize, desired);
            } else {
                // 如果MeasureSpec的Mode是UNSPECIFIED则最终的值直接等于实际测量的值
                height = desired;
            }
        }

        // 设置测量的宽高
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        // 绘制一个蓝色矩形的背景
        mPaint.setColor(Color.BLUE);
        canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), mPaint);

        // 设置字体颜色
        mPaint.setColor(mCustomTitleTextColor);
        // 设置字体大小
        mPaint.setTextSize(mCustomTitleTextSize);
        // 获取文字的边界
        mPaint.getTextBounds(mCustomTitleText, 0, mCustomTitleText.length(), mBound);
        // 绘制文字
        canvas.drawText(mCustomTitleText,
                getWidth() / 2 - mBound.width() / 2,
                getHeight() / 2 + mBound.height() / 2,
                mPaint);
    }

    // 触摸事件处理
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // 随机数Text
                mCustomTitleText = randomText();
                // 重绘
                invalidate();
                break;
        }
        return true;
    }

    // 随机数Text
    private String randomText() {
        // 随机数
        Random random = new Random();
        // 要求数字不能相同
        Set<Integer> set = new HashSet<>();

        // 循环4次
        while (set.size() < 4) {
            // [0,10)中的随机数
            int randomInt = random.nextInt(10);
            set.add(randomInt);
        }

        // 将数字串连在一起
        StringBuffer sb = new StringBuffer();
        for (Integer i : set) {
            sb.append("" + i);
        }

        return sb.toString();
    }
}

其中,invalidate()在UI线程中调用,postInvalidate()在非UI线程中调用,都是重绘的意思就是会重新调用View的onDraw()方法。

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.jun.androidexample.customview.CustomTitleView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:padding="12dp"
        custom:customTitleText="8745"
        custom:customTitleTextColor="#ff0000"
        custom:customTitleTextSize="30sp"/>
</RelativeLayout>

MianActivity.java

public class MianActivity extends AppCompatActivity {

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

参考

Android 自定义View (一)

相关文章

网友评论

      本文标题:自定义View的简单流程

      本文链接:https://www.haomeiwen.com/subject/drunjttx.html