Android進階之自定義View(1)實現可換行的TextView
今天來一起學習一下最簡單的自定義view,自己動手寫一個MyTextView,當然不會像系統的TextView那麼複雜,只是實現一下TextView的簡單功能,包括分行顯示及自定義屬性的處理,主要目的是介紹自定義view的實現的基本思路和需要掌握的一些基礎知識。
《一》先展示一下實現的最終效果
《二》實現步驟分析
1、建立MyTextView extends View,重寫構造方法。一般是重寫前三個構造方法,讓前兩個構造方法最終呼叫三個引數的構造方法,然後在第三個構造方法中進行一些初始化操作。
2、在構造方法中進行一些初始化操作,如初始化畫筆及獲取自定義屬性等。
如何自定義屬性?
(1)在values下建立attrs.xml.
//定義你的view可以在佈局檔案中配置的自定義屬性 <declare-styleable name="MyTextViewApprence"> <attr name="textColor" format="color"></attr> <attr name="textSize" format="dimension"></attr> <attr name="text" format="string"></attr> <attr name="showMode"> <enum name="left" value="0" /> <enum name="center" value="1" /> </attr> </declare-styleable>
(2)獲取自定義屬性
TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyTextViewApprence, defStyleAttr, 0); mText = typedArray.getString(R.styleable.MyTextViewApprence_text); mTextColor = typedArray.getColor(R.styleable.MyTextViewApprence_textColor, Color.BLACK); mTextSize = (int) typedArray.getDimension(R.styleable.MyTextViewApprence_textSize, 15); showMode = typedArray.getInt(R.styleable.MyTextViewApprence_showMode, 0); typedArray.recycle();
3、重寫OnDraw()方法,在onDraw()中使用carvas繪製文字,x,y為繪製的起點。
需要注意兩點:
(1)這裡的x,y不是指的左上頂點,而是左下頂點。
(2)drawText繪製文字時,是有規則的,這個規則就是基線!詳細可閱讀drawText()詳解
//繪製每行文字的建議高度為:
Paint.FontMetrics fm = mPaint.getFontMetrics();
drawTextHeight = (int) (fm.descent - fm.ascent);
繪製文字的方法:
canvas.drawText(@NonNull String text, float x, float y, @NonNull Paint paint)
4、到第三步,其實就可以繪製出文字了,但是會發現一個問題,無論在佈局檔案中宣告控制元件的寬高是wrap_content和match_parent,效果都是鋪滿了整個螢幕,這個時候,我們就需要重寫onMesure()方法來測量控制元件的實際大小了,分析View的原始碼:
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
public static int getDefaultSize(int size, int measureSpec) {
int result = size;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
switch (specMode) {
case MeasureSpec.UNSPECIFIED:
result = size;
break;
case MeasureSpec.AT_MOST:
case MeasureSpec.EXACTLY:
result = specSize;
break;
}
return result;
}
/**MeasureSpec 封裝了父控制元件對其孩子的佈局要求
有大小和模式兩種,而模式則有三種模式
public static class MeasureSpec {
private static final int MODE_SHIFT = 30;
private static final int MODE_MASK = 0x3 << MODE_SHIFT;
//父控制元件不強加任何約束給子控制元件,它可以為它逍遙的任何大小
public static final int UNSPECIFIED = 0 << MODE_SHIFT; //0
//父控制元件給子控制元件一個精確的值
public static final int EXACTLY = 1 << MODE_SHIFT; //1073741824
//父控制元件給子控制元件竟可能最大的值
public static final int AT_MOST = 2 << MODE_SHIFT; //-2147483648
//設定尺寸和模式建立的統一約束規範
public static int makeMeasureSpec(int size, int mode) {
if (sUseBrokenMakeMeasureSpec) {
return size + mode;
} else {
return (size & ~MODE_MASK) | (mode & MODE_MASK);
}
}
// 從規範中獲取模式
public static int getMode(int measureSpec) {
return (measureSpec & MODE_MASK);
}
//從規範中獲取尺寸
public static int getSize(int measureSpec) {
return (measureSpec & ~MODE_MASK);
}
}
關於specMode測量的幾種模式,你需要知道它們的作用,如下圖。
可以看到我們的原始碼中呼叫是自身的getDefaultSize()方法,然後在MeasureSpec.AT_MOST和MeasureSpec.EXACTLY全部返回的是specSize,而specSize表示的是父控制元件剩餘寬度,也就是我們看到的全屏。所以預設onMeasure方法中wrap_content 和match_parent 的效果是一樣的,都是填充剩餘的空間。所以我們重新onMesure()方法,對wrap_content這種情況進行處理。
@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);
Log.e("TAG", "widthMode=" + widthMode + " heightMode=" + heightMode + " widthSize=" + widthSize + " heightSize=" + heightSize);
//對wrap_content這種模式進行處理
int width;
int height;
if (widthMode == MeasureSpec.EXACTLY) {
width = widthSize;
} else {
//如果是wrap_content,我們需要得到控制元件需要多大的尺寸
//首先丈量文字的寬度
float textWidth;
textWidth = mTextBoundOther.width();
//控制元件的寬度就是文字的寬度加上兩邊的內邊距。內邊距就是padding的值,在構造方法執行完被賦值
width = (int) (getPaddingLeft() + textWidth + getPaddingRight());
}
if (heightMode == MeasureSpec.EXACTLY) {
height = heightSize;
} else {
//如果是wrap_content,我們需要得到控制元件需要多大的尺寸
//首先丈量文字的寬度
float textHeight = mTextBoundOther.height();
//控制元件的寬度就是文字的寬度加上兩邊的內邊距。內邊距就是padding的值,在構造方法執行完被賦值。遺留問題:最後一行顯示高度不夠,在這裡加上10px處理
height = (int) (getPaddingTop() + textHeight + getPaddingBottom() + 10);
}
//儲存丈量結果
setMeasuredDimension(width, height);
}
下面是實現了自動換行的TextView的完整程式碼:
package com.example.jojo.learn.customview;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import com.example.jojo.learn.R;
import java.util.ArrayList;
/**
* Created by JoJo on 2018/7/27.
* wechat:18510829974
* description:自定義Textview
*/
public class MyTextView extends View {
//文字內容
private String mText;
//文字大小
private int mTextSize;
//文字顏色
private int mTextColor;
//繪製的範圍
private Rect mTextBound;
//繪製文字的畫筆
private Paint mPaint;
private int mScreenWidth;
private int mScreenHeight;
private int baseLineY;
private float ascent;
private float descent;
private float top;
private float bottom;
private int baseLineX;
private Rect mMaxRect;
private Rect mTextBoundOther;
private String text = "This is a great day";
private int drawTextHeight;
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 typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyTextViewApprence, defStyleAttr, 0);
mText = typedArray.getString(R.styleable.MyTextViewApprence_text);
mTextColor = typedArray.getColor(R.styleable.MyTextViewApprence_textColor, Color.BLACK);
mTextSize = (int) typedArray.getDimension(R.styleable.MyTextViewApprence_textSize, 15);
showMode = typedArray.getInt(R.styleable.MyTextViewApprence_showMode, 0);
typedArray.recycle();
//螢幕資訊
DisplayMetrics dm = getResources().getDisplayMetrics();
mScreenHeight = dm.heightPixels;
mScreenWidth = dm.widthPixels;
if (TextUtils.isEmpty(mText)) {
mText = "Hello.....Hello.....Hello.....Hello.....Hello.....Hello.....Hello.....Hello.....Hello.....Hello.....Hello....";
}
init();
}
private void init() {
//基線
baseLineY = mTextSize;
baseLineX = 0;
//初始化畫筆
mPaint = new Paint();
mPaint.setColor(mTextColor);
mPaint.setTextSize(mTextSize);
mPaint.setAntiAlias(true);
mPaint.setStrokeWidth(1);
//獲取繪製的寬高
mTextBound = new Rect();
mPaint.getTextBounds(text, 0, text.length(), mTextBound);
mTextBound.top = baseLineY + mTextBound.top;
mTextBound.bottom = baseLineY + mTextBound.bottom;
mTextBound.left = baseLineX + mTextBound.left;
mTextBound.right = baseLineX + mTextBound.right;
//獲取文字所佔區域最小矩形
Log.e("TAG", mTextBound.toShortString());
//換行的文字
mTextBoundOther = new Rect();
mPaint.getTextBounds(mText, 0, mText.length(), mTextBoundOther);
//計算各線在位置
Paint.FontMetrics fm = mPaint.getFontMetrics();
ascent = baseLineY + fm.ascent;//當前繪製頂線
descent = baseLineY + fm.descent;//當前繪製底線
top = baseLineY + fm.top;//可繪製最頂線
bottom = baseLineY + fm.bottom;//可繪製最低線
//每行文字的繪製高度
drawTextHeight = (int) (fm.descent - fm.ascent);
//字串所佔的高度和寬度
int width = (int) mPaint.measureText(mText);
int height = (int) (bottom - top);
//文字繪製時可以佔據的最大矩形區域
mMaxRect = new Rect(baseLineX, (int) (baseLineY + fm.top), (baseLineX + width), (int) (baseLineY + fm.bottom));
}
private ArrayList<String> mTextList = new ArrayList<>();
private float lineNum;//文字最終所佔的行數
private float spLineNum;
//換行展示的對齊方式
private int showMode;
/**
* 測量
* 父控制元件不強加任何約束給子控制元件,它可以為它逍遙的任何大小
* public static final int UNSPECIFIED = 0 << MODE_SHIFT; //0
* 父控制元件給子控制元件一個精確的值-match_parent
* public static final int EXACTLY = 1 << MODE_SHIFT; //1073741824
* 父控制元件給子控制元件竟可能最大的值-wrap_content
* public static final int AT_MOST = 2 << MODE_SHIFT; //-2147483648
*
* @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);
Log.e("TAG", "widthMode=" + widthMode + " heightMode=" + heightMode + " widthSize=" + widthSize + " heightSize=" + heightSize);
//(1)實現文字自動換行顯示
//文字的寬度
int mTextWidth = mTextBoundOther.width();
if (mTextList.size() == 0) {
//將文字分段
int padding = getPaddingLeft() + getPaddingRight();
int specMaxWidth = widthSize - padding;//可顯示文字的最大寬度
//最大寬度大於文字所佔寬度,則一行就能顯示完全
if (specMaxWidth >= mTextWidth) {
lineNum = 1;
mTextList.add(mText);
} else {
//超過一行,需切割,分行顯示
spLineNum = mTextWidth * 1.0f / specMaxWidth;
//如果有小數的話就進1
if ((spLineNum + "").contains(".")) {
lineNum = (float) (spLineNum + 0.5);
} else {
lineNum = spLineNum;
}
//每行展示的文字的長度
int lineLength = (int) (mText.length() / spLineNum);
for (int i = 0; i < lineNum; i++) {
String lineStr;
//判斷是否可以一行展示
if (mText.length() < lineLength) {
lineStr = mText.substring(0, mText.length());
} else {
lineStr = mText.substring(0, lineLength);
}
mTextList.add(lineStr);
//內容切割完,記錄切割後的字串,重新賦值給mText
if (!TextUtils.isEmpty(mText)) {
if (mText.length() < lineLength) {
mText = mText.substring(0, mText.length());
} else {
mText = mText.substring(lineLength, mText.length());
}
} else {
break;
}
}
}
}
//(2)下面對wrap_content這種模式進行處理
int width;
int height;
if (widthMode == MeasureSpec.EXACTLY) {
width = widthSize;
} else {
//如果是wrap_content,我們需要得到控制元件需要多大的尺寸
//首先丈量文字的寬度
float textWidth;
if (mTextList.size() > 1) {
textWidth = widthSize;
} else {
textWidth = mTextBoundOther.width();
}
//控制元件的寬度就是文字的寬度加上兩邊的內邊距。內邊距就是padding的值,在構造方法執行完被賦值
width = (int) (getPaddingLeft() + textWidth + getPaddingRight());
}
if (heightMode == MeasureSpec.EXACTLY) {
height = heightSize;
} else {
//如果是wrap_content,我們需要得到控制元件需要多大的尺寸
//首先丈量文字的寬度
// float textHeight = mTextBoundOther.height();
float textHeight = drawTextHeight * mTextList.size();
//控制元件的寬度就是文字的寬度加上兩邊的內邊距。內邊距就是padding的值,在構造方法執行完被賦值。遺留問題:最後一行顯示高度不夠,在這裡加上10px處理
height = (int) (getPaddingTop() + textHeight + getPaddingBottom() + 10);
}
//儲存丈量結果
setMeasuredDimension(width, height);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
/**
* 測試文字的繪製區域
*/
// //繪製字串所佔的矩形區域
// mPaint.setColor(Color.GREEN);
// canvas.drawRect(mMaxRect, mPaint);
//
// //繪製最小矩形
// mPaint.setColor(Color.RED);
// canvas.drawRect(mTextBound, mPaint);
//
// //繪製文字-繪製的起點是:繪製文字所在矩形的左下角頂點
// mPaint.setColor(Color.WHITE);
// canvas.drawText(text, baseLineX, baseLineY, mPaint);
//
// //繪製基線
// mPaint.setColor(Color.RED);
// canvas.drawLine(0, baseLineY, mScreenWidth, baseLineY, mPaint);
//
// mPaint.setColor(Color.YELLOW);
// canvas.drawLine(0, top, mScreenWidth, top, mPaint);
// mPaint.setColor(Color.GREEN);
// canvas.drawLine(0, ascent, mScreenWidth, ascent, mPaint);
// mPaint.setColor(Color.BLACK);
// canvas.drawLine(0, descent, mScreenWidth, descent, mPaint);
// mPaint.setColor(Color.WHITE);
// canvas.drawLine(0, bottom, mScreenWidth, bottom, mPaint);
// 繪製Hello World !
// canvas.drawText(text, getWidth() / 2 - mTextBoundOther.width() / 2, getHeight() / 2 + mTextBoundOther.height() / 2, mPaint);
//分行繪製文字
for (int i = 0; i < mTextList.size(); i++) {
mPaint.getTextBounds(mTextList.get(i), 0, mTextList.get(i).length(), mTextBoundOther);
//換行左對齊展示
if (showMode == 0) {
canvas.drawText(mTextList.get(i), 0 + getPaddingLeft(), (getPaddingTop() + drawTextHeight * (i + 1)), mPaint);
} else if (showMode == 1) {
//換行居中展示
canvas.drawText(mTextList.get(i), (getWidth() / 2 - mTextBoundOther.width() / 2) + getPaddingLeft(), (getPaddingTop() + drawTextHeight * (i + 1)), mPaint);
}
}
}
/**
* 控制文字對齊方式:居中或者居左
*
* @param showMode
*/
public void reLayoutText(int showMode) {
this.showMode = showMode;
invalidate();
}
}
涉及到的自定義屬性:attrs.xml中
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyTextViewApprence">
<attr name="textColor" format="color"></attr>
<attr name="textSize" format="dimension"></attr>
<attr name="text" format="string"></attr>
<attr name="showMode">
<enum name="left" value="0" />
<enum name="center" value="1" />
</attr>
</declare-styleable>
</resources>
在佈局檔案中使用,測試程式碼:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:mytext="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorAccent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/white"
android:onClick="textLayoutLeft"
android:text="文字居左對齊" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:background="@android:color/white"
android:onClick="textLayoutCenter"
android:text="文字居中對齊" />
<com.example.jojo.learn.customview.MyTextView
android:id="@+id/mytextview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="@android:color/holo_red_dark"
mytext:showMode="center"
mytext:text="來一碗大的毒雞湯:無論做什麼事情,你首先要想到的不是你能得到什麼,而是你能接受失去什麼,當你無畏失去什麼的時候,你就變得無敵了。人生最重要的不是所站的位置是所站的位置是所站的位置是所站的位置是所站的位置你來自何處並不重要,重要的是你要去往何方,人生最重要的不是所站的位置,而是所去的方向。人只要不失去方向,就永遠不會失去自己!無論做什麼事情,你首先要想到的不是你能得到什麼,而是你能接受失去什麼,當你無畏失去什麼的時候,你就變得無敵了"
mytext:textColor="@android:color/white"
mytext:textSize="50px" />
</RelativeLayout>
歡迎各位讀者一起來探索下面的待解決的問題:
1、中英文混排時展示有問題
2、最後一行測量給的高度不夠,導致最後一行展示不全
3、textSize的單位,在佈局檔案中沒有處理成sp,而是px。如果需要處理成sp,可以參考系統TextView原始碼。
mTextSize = (int) typedArray.getDimension(R.styleable.MyTextViewApprence_textSize, sp2px(mTextSize));
/**
* 將sp轉換成px
*
* @param sp
* @return
*/
private int sp2px(int sp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp,
getResources().getDisplayMetrics());
}