美文网首页
自定义view - 自定义TextView

自定义view - 自定义TextView

作者: 世道无情 | 来源:发表于2019-02-12 18:02 被阅读0次

1. 思路分析


自定义View步骤:
1>:values__attrs.xml,自定义属性;
2>:在第三个构造方法中获取自定义属性;
3>:onMeasure:不是非必须的;
4>:onDraw:所有绘制的代码都写在onDraw方法中;

步骤分析:
1>:在values__attrs中定义自定义属性;
2>:自定义MyTextView;
3>:在activity_mytextview布局文件中使用;

效果图如下:
图片.png
1>:values__attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <!-- 自定义View的名字 -->
    <declare-styleable name="MyTextView">

        <!-- 以下是所用到的属性-->

        <!-- 文字-string -->
        <attr name="novateText" format="string"/>
        <!-- 文字大小-dimension -->
        <attr name="novateTextSize" format="dimension"/>
        <!-- 文字长度-->
        <attr name="novateMaxLength" format="integer"/>
        <!-- 文字颜色-color-->
        <attr name="novateColor" format="color"/>

        <!-- 枚举 -->
        <attr name="novateInputType">
            <enum name="number" value="1"/>
            <enum name="text" value="2"/>
            <enum name="password" value="3"/>
        </attr>

    </declare-styleable>
</resources>
2>:MyTextView
/**
 * ================================================
 * Email: 2185134304@qq.com
 * Created by Novate 2018/12/28 10:52
 * Version 1.0
 * Params:
 * Description:    自定义TextView
 * ================================================
*/

public class MyTextView extends View {

    // 文字
    private String mText ;
    // 文字默认大小 15sp
    private int mTextSize = 15 ;
    // 文字默认颜色
    private int mTextColor = Color.BLACK ;
    // 初始化画笔
    private Paint mPaint ;

    /**
     * 这种调用第1个构造方法
     * TextView tv = new TextView(this):
     */
    public MyTextView(Context context) {
        this(context,null);
    }

    /**
     * 这种调用第2个构造方法
     * <com.novate.test.customview.MyTextView
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             app:novateText="北京Novate"
             app:novateTextSize="20sp"
             app:novateColor="#ff0000"
             android:background="#00FF00"
             />
     */
    public MyTextView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    /**
     * 这个和第二个方法一样,只是该布局文件中含有 style属性
     */
    public MyTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        // 获取自定义属性
        TypedArray typedArray = context.obtainStyledAttributes(attrs , R.styleable.MyTextView) ;
        // 获取文字
        mText = typedArray.getString(R.styleable.MyTextView_novateText) ;
        // 获取文字大小
        mTextSize = typedArray.getDimensionPixelSize(R.styleable.MyTextView_novateTextSize , sp2px(mTextSize)) ;
        // 获取文字颜色
        typedArray.getColor(R.styleable.MyTextView_novateColor , mTextColor) ;
        // 释放资源
        typedArray.recycle();

        // 创建画笔
        mPaint = new Paint() ;
        // 设置抗锯齿,让文字比较清晰,同时文字也会变得圆滑
        mPaint.setAntiAlias(true);
        // 设置文字大小
        mPaint.setTextSize(mTextSize);
        // 设置画笔颜色
        mPaint.setColor(mTextColor);
    }


    /**
     * 测量文字
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        // TODO:方式1:如果在布局文件中设置的宽高都是固定值[比如100dp、200dp等],就用下边方式直接获取宽高
        int width = MeasureSpec.getSize(widthMeasureSpec) ;
        int height = MeasureSpec.getSize(heightMeasureSpec) ;



        //  TODO:方式2:如果调用者在布局文件给自定义MyTextView的宽高属性设置wrap_content,
        // 就需要通过下边的 widthMode和heightMode来获取宽高
        // 获取宽高模式
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        // 如果在布局中设置宽高都是wrap_content[对应AT_MOST],必须用mode计算
        if (widthMode == MeasureSpec.AT_MOST){
            // 文字宽度 与字体大小和长度有关
            Rect rect = new Rect() ;
            // 获取文本区域 param1__测量的文字 param2__从位置0开始 param3__到文字长度
            mPaint.getTextBounds(mText , 0 , mText.length() , rect);
            // 文字宽度 getPaddingLeft宽度 getPaddingRight高度 写这两个原因是为了在布局文件中设置padding属性起作用
            width = rect.width() + getPaddingLeft() + getPaddingRight() ;
        }

        if (heightMode == MeasureSpec.AT_MOST){
            Rect rect = new Rect() ;
            mPaint.getTextBounds(mText , 0 , mText.length() , rect);
            height = rect.height() + getPaddingTop() + getPaddingBottom() ;
        }

        // 给文字设置宽高
        setMeasuredDimension(width , height);
    }


    /**
     * 绘制文字
     */
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint.FontMetricsInt fontMetricsInt = mPaint.getFontMetricsInt();
        int dy = (fontMetricsInt.bottom - fontMetricsInt.top)/2 - fontMetricsInt.bottom ;
        int baseLine = getHeight()/2 + dy ;
        int x = getPaddingLeft() ;
        canvas.drawText(mText , x , baseLine , mPaint);
    }

    /**
     *  sp转为px
     */
    private int sp2px(int sp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp,
                getResources().getDisplayMetrics());
    }
}
3>:activity_mytextview
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.novate.test.customview.MyTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:novateText="北京Novate"
        app:novateTextSize="20sp"
        app:novateColor="#ff0000"
        android:background="#00FF00"
        />
</LinearLayout>
4>:MyTextViewActivity
public class MyTextViewActivity extends AppCompatActivity {
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mytextview);
    }
}

相关文章

网友评论

      本文标题:自定义view - 自定义TextView

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