自定义View实战一:打造仿系统TextView

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Androidtalent/article/details/80461937

自定义 View 是较为重要的一个技能,Android 的日常开发离不开自定义 View,下面以仿系统 TextView 进行对自定义 View 的学习与分析,本例只是初步实现 TextView 的基本功能,对于完整的 TextView 功能,还需一定程度上的源码分析。

第一步:继承 LinearLayout,做好初始化工作

初始化分析,需在构造方法中实现以下关键的操作:
- 将构造方法始终调用三个参数的构造方法,使得初始化操作被实现
- 准备好属性对应的字段:内容、颜色、字号大小
- 准备好画笔,以便绘制操作
代码

public class MyTextView extends LinearLayout {

    private String mText;                       // 内容
    private int mTextSize = 15;                 // 字号大小,默认 15
    private int mTextColor = Color.BLACK;       // 颜色,默认 黑色

    private Paint mPaint;                       // 画笔

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

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

    public MyTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr){
        super(context, attrs, defStyleAttr);

        // 获取自定义属性
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MyTextView);

        mText = array.getString(R.styleable.MyTextView_VegenText);
        if (mText == null) mText = "";      // 默认为 ""
        mTextColor = array.getColor(R.styleable.MyTextView_VegenTextColor, mTextColor);
        mTextSize = array.getDimensionPixelSize(R.styleable.MyTextView_VegenTextSize,sp2px(mTextSize));

        // 回收
        array.recycle();

        mPaint = new Paint();
        // 抗锯齿
        mPaint.setAntiAlias(true);
        // 设置字体的大小和颜色
        mPaint.setTextSize(mTextSize);
        mPaint.setColor(mTextColor);

        // 重写 onDraw 需要,去掉其WILL_NOT_DRAW flag
        setWillNotDraw(false);
    }

    private int sp2px(int sp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,sp,
                getResources().getDisplayMetrics());
    }
}

第二步:重写 onMeasure() 方法

分析,需实现以下关键的操作:
- 获取宽高的模式
- 获取宽高的值
- 计算的宽高,设置控件的宽高
代码

/**
     * 自定义View的测量方法
     * @param widthMeasureSpec
     * @param heightMeasureSpec
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // 布局的宽高都是由这个方法指定
        // 指定控件的宽高,需要测量
        // 获取宽高的模式
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        // 1.确定的值,这个时候不需要计算,给的多少就是多少
        int width = MeasureSpec.getSize(widthMeasureSpec);

        // 2.给的是wrap_content 需要计算
        if(widthMode == MeasureSpec.AT_MOST){
            // 计算的宽度 与 字体的长度有关  与字体的大小  用画笔来测量
            Rect bounds = new Rect();
            // 获取文本的Rect
            mPaint.getTextBounds(mText, 0, mText.length(), bounds);
            width = bounds.width() + getPaddingLeft() + getPaddingRight();
        }

        int height = MeasureSpec.getSize(heightMeasureSpec);

        if(widthMode == MeasureSpec.AT_MOST){
            // 计算的宽度 与 字体的长度有关  与字体的大小  用画笔来测量
            Rect bounds = new Rect();
            // 获取文本的Rect
            mPaint.getTextBounds(mText, 0, mText.length(), bounds);
            height = bounds.height() + getPaddingTop() + getPaddingBottom();
        }

        // 设置控件的宽高
        setMeasuredDimension(width,height);
    }

第三步:重写 onDraw() 方法

分析,需实现以下关键的操作:
- 计算 baseLine
- 画字
代码

/**
     * 绘制
     * @param canvas
     */
    @Override
    protected void onDraw(Canvas canvas) {
        super.dispatchDraw(canvas);
        // x 就是开始的位置
        // y 基线 baseLine
        // dy 代表的是:高度的一半到 baseLine的距离
        Paint.FontMetricsInt fontMetrics = mPaint.getFontMetricsInt();
        // top 是一个负值  bottom 是一个正值    top,bttom的值代表是  bottom 是baseLin e到文字底部的距离(正值)
        int dy = (fontMetrics.bottom - fontMetrics.top)/2 - fontMetrics.bottom;
        int baseLine = getHeight()/2 + dy;
        int x = getPaddingLeft();
        canvas.drawText(mText,x,baseLine,mPaint);
    }

最终的效果

xiaoguotu.jpg

本文涉及的完整源码如下

public class MyTextView extends LinearLayout {

    private String mText;                       // 内容
    private int mTextSize = 15;                 // 字号大小,默认 15
    private int mTextColor = Color.BLACK;       // 颜色,默认 黑色

    private Paint mPaint;                       // 画笔

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

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

    public MyTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr){
        super(context, attrs, defStyleAttr);

        // 获取自定义属性
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MyTextView);

        mText = array.getString(R.styleable.MyTextView_VegenText);
        if (mText == null) mText = "";      // 默认为 ""
        mTextColor = array.getColor(R.styleable.MyTextView_VegenTextColor, mTextColor);
        mTextSize = array.getDimensionPixelSize(R.styleable.MyTextView_VegenTextSize,sp2px(mTextSize));

        // 回收
        array.recycle();

        mPaint = new Paint();
        // 抗锯齿
        mPaint.setAntiAlias(true);
        // 设置字体的大小和颜色
        mPaint.setTextSize(mTextSize);
        mPaint.setColor(mTextColor);

        // 重写 onDraw 需要,去掉其WILL_NOT_DRAW flag
        setWillNotDraw(false);
    }

    private int sp2px(int sp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,sp,
                getResources().getDisplayMetrics());
    }

    /**
     * 自定义View的测量方法
     * @param widthMeasureSpec
     * @param heightMeasureSpec
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // 布局的宽高都是由这个方法指定
        // 指定控件的宽高,需要测量
        // 获取宽高的模式
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        // 1.确定的值,这个时候不需要计算,给的多少就是多少
        int width = MeasureSpec.getSize(widthMeasureSpec);

        // 2.给的是wrap_content 需要计算
        if(widthMode == MeasureSpec.AT_MOST){
            // 计算的宽度 与 字体的长度有关  与字体的大小  用画笔来测量
            Rect bounds = new Rect();
            // 获取文本的Rect
            mPaint.getTextBounds(mText, 0, mText.length(), bounds);
            width = bounds.width() + getPaddingLeft() + getPaddingRight();
        }

        int height = MeasureSpec.getSize(heightMeasureSpec);

        if(widthMode == MeasureSpec.AT_MOST){
            // 计算的宽度 与 字体的长度有关  与字体的大小  用画笔来测量
            Rect bounds = new Rect();
            // 获取文本的Rect
            mPaint.getTextBounds(mText, 0, mText.length(), bounds);
            height = bounds.height() + getPaddingTop() + getPaddingBottom();
        }

        // 设置控件的宽高
        setMeasuredDimension(width,height);
    }

    /**
     * 绘制
     * @param canvas
     */
    @Override
    protected void onDraw(Canvas canvas) {
        super.dispatchDraw(canvas);
        // x 就是开始的位置
        // y 基线 baseLine
        // dy 代表的是:高度的一半到 baseLine的距离
        Paint.FontMetricsInt fontMetrics = mPaint.getFontMetricsInt();
        // top 是一个负值  bottom 是一个正值    top,bttom的值代表是  bottom 是baseLin e到文字底部的距离(正值)
        int dy = (fontMetrics.bottom - fontMetrics.top)/2 - fontMetrics.bottom;
        int baseLine = getHeight()/2 + dy;
        int x = getPaddingLeft();
        canvas.drawText(mText,x,baseLine,mPaint);
    }
}
<resources>
    <!--name 自定义View的名字 MyTextView-->
    <declare-styleable name="MyTextView">
        <!-- name 属性名称

        format 格式: string 文字  color 颜色
                    dimension 宽高 字体大小  integer 数字
                    reference 资源(drawable)
         -->
        <attr name="VegenText" format="string"/>
        <attr name="VegenTextColor" format="color"/>
        <attr name="VegenTextSize" format="dimension"/>
        <attr name="VegenMaxLength" format="integer"/>

        <!-- 枚举 -->
        <attr name="VegenInputType">
            <enum name="number" value="1"/>
            <enum name="text" value="2"/>
            <enum name="password" value="3"/>
        </attr>
    </declare-styleable>
</resources>

猜你喜欢

转载自blog.csdn.net/Androidtalent/article/details/80461937