自定义View的简单流程

自定义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 (一)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 162,710评论 4 376
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,839评论 2 308
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 112,295评论 0 255
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,776评论 0 223
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 53,198评论 3 297
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 41,074评论 1 226
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,200评论 2 322
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,986评论 0 214
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,733评论 1 250
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,877评论 2 254
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,348评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,675评论 3 265
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,393评论 3 246
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,209评论 0 9
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,996评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,212评论 2 287
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 36,003评论 2 280

推荐阅读更多精彩内容