Android自定義TextView


1.自定義屬性

新建attrs.xml文件(res->values->attrs.xml),定義要自定義的TextView屬性

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyTextView">

        <!--name 屬性名稱 format 格式-->
        <attr name="myText" format="string" />
        <attr name="myTextColor" format="color" />
        <attr name="myTextSize" format="dimension" />

    </declare-styleable>
</resources>

2.在布局中使用,對比系統TextView

<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <com.future.coding.custom_view.MyTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        app:myText="set a flag"
        app:myTextColor="#D81B60"
        app:myTextSize="16sp" />


    <!--與上面自定義TextView的對比-->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="set a flag"
        android:textColor="#D81B60"
        android:textSize="16sp" />

</LinearLayout>

3.通過繼承View,實現自定義TextView

public class MyTextView extends View {

    private String mText;
    private int mTextSize = 16;
    private int mTextColor = Color.BLACK;

    private Paint mPaint;

    private static final String TAG = "MyTextView";

    //在代碼中使用
    public MyTextView(Context context) {
        this(context, null);
    }

    //在布局layout中使用
    public MyTextView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    //在布局layout中使用,但會有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_myText);
        mTextColor = typedArray.getColor(R.styleable.MyTextView_myTextColor, mTextColor);

        Log.d(TAG, "MyTextView: " + sp2px(mTextSize));
        mTextSize = typedArray.getDimensionPixelSize(R.styleable.MyTextView_myTextSize, sp2px(mTextSize));


        /**
         * 解析:TypedArray 為什么需要調用recycle()
         * https://blog.csdn.net/Monicabg/article/details/45014327
         */
        typedArray.recycle();

        mPaint = new Paint();
        mPaint.setAntiAlias(true);//抗鋸齒
        mPaint.setTextSize(mTextSize);
        mPaint.setColor(mTextColor);
    }


    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);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        if (widthMode == MeasureSpec.AT_MOST) {//在布局中指定了wrap_content

            Rect bounds = new Rect();
            mPaint.getTextBounds(mText, 0, mText.length(), bounds);
            widthSize = bounds.width() + getPaddingLeft() + getPaddingRight();
        } else if (widthMode == MeasureSpec.EXACTLY) {//在布局中指定了確定的值 比如:100dp / match_parent

        } else if (widthMode == MeasureSpec.UNSPECIFIED) {//盡可能的大,很少能用到
            //ListView、ScrollView在測量子布局的時候會用
        }


        if (heightMode == MeasureSpec.AT_MOST) {//在布局中指定了wrap_content

            Rect bounds = new Rect();
            mPaint.getTextBounds(mText, 0, mText.length(), bounds);
            heightSize = bounds.height() + getPaddingTop() + getPaddingBottom();
        } else if (heightMode == MeasureSpec.EXACTLY) {//在布局中指定了確定的值  比如:100dp / match_parent

        } else if (heightMode == MeasureSpec.UNSPECIFIED) {//盡可能的大,很少能用到
            //ListView、ScrollView在測量子布局的時候會用
        }

        setMeasuredDimension(widthSize, heightSize);

    }

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

     /**
         * 自定義控件之繪圖篇( 五):drawText()詳解
         * https://blog.csdn.net/harvic880925/article/details/50423762
         */
        Paint.FontMetrics fontMetrics = mPaint.getFontMetrics();
        //中心線到基線的距離(當前情況不適用)
        //int dy = (int) ((fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom);
        //更正
        //onMeasure()方法設置的文字范圍對應着“當前繪制頂線(ascent)”和“當前繪制底線(descent)”,並非“可繪制最頂線(top)”和“可繪制最底線(bottom)”
        //getHeight()得到的onMeasure()方法中的高度,此時中心線並不是bottom-top的中心(如果使用會出現文字顯示不全的現象),而應該是descent-ascent的中心
     //中心線到基線的距離
        int dy = (fontMetrics.descent - fontMetrics.ascent) / 2 - fontMetrics.descent;

        //得到基線(BaseLine) 
        int baseLine = getHeight() / 2 + dy;

        int x = getPaddingLeft();
        canvas.drawText(mText, x, baseLine, mPaint);
    }

}
       

  

--END

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM