源碼
BaselineGridTextView是繼承FontTextView的一個自定義控件:
/**
* An extension to {@link android.widget.TextView} which aligns text to a 4dp baseline grid.
* <p>
* To achieve this we expose a {@code lineHeightHint} allowing you to specify the desired line
* height (alternatively a {@code lineHeightMultiplierHint} to use a multiplier of the text size).
* This line height will be adjusted to be a multiple of 4dp to ensure that baselines sit on
* the grid.
* <p>
* We also adjust spacing above and below the text to ensure that the first line's baseline sits on
* the grid (relative to the view's top) & that this view's height is a multiple of 4dp so that
* subsequent views start on the grid.
*/
public class BaselineGridTextView extends FontTextView {
private final float FOUR_DIP;
private float lineHeightMultiplierHint = 1f;
private float lineHeightHint = 0f;
private boolean maxLinesByHeight = false;
private int extraTopPadding = 0;
private int extraBottomPadding = 0;
public BaselineGridTextView(Context context) {
this(context, null);
}
public BaselineGridTextView(Context context, AttributeSet attrs) {
this(context, attrs, android.R.attr.textViewStyle);
}
public BaselineGridTextView(Context context, AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
public BaselineGridTextView(Context context, AttributeSet attrs,
int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
final TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.BaselineGridTextView, defStyleAttr, defStyleRes);
lineHeightMultiplierHint =
a.getFloat(R.styleable.BaselineGridTextView_lineHeightMultiplierHint, 1f);
lineHeightHint =
a.getDimensionPixelSize(R.styleable.BaselineGridTextView_lineHeightHint, 0);
maxLinesByHeight = a.getBoolean(R.styleable.BaselineGridTextView_maxLinesByHeight, false);
a.recycle();
FOUR_DIP = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 4, getResources().getDisplayMetrics());
computeLineHeight();
}
public float getLineHeightMultiplierHint() {
return lineHeightMultiplierHint;
}
public void setLineHeightMultiplierHint(float lineHeightMultiplierHint) {
this.lineHeightMultiplierHint = lineHeightMultiplierHint;
computeLineHeight();
}
public float getLineHeightHint() {
return lineHeightHint;
}
public void setLineHeightHint(float lineHeightHint) {
this.lineHeightHint = lineHeightHint;
computeLineHeight();
}
public boolean getMaxLinesByHeight() {
return maxLinesByHeight;
}
public void setMaxLinesByHeight(boolean maxLinesByHeight) {
this.maxLinesByHeight = maxLinesByHeight;
requestLayout();
}
@Override
public int getCompoundPaddingTop() {
// include extra padding to place the first line's baseline on the grid
return super.getCompoundPaddingTop() + extraTopPadding;
}
@Override
public int getCompoundPaddingBottom() {
// include extra padding to make the height a multiple of 4dp
return super.getCompoundPaddingBottom() + extraBottomPadding;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
extraTopPadding = 0;
extraBottomPadding = 0;
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int height = getMeasuredHeight();
height += ensureBaselineOnGrid();
height += ensureHeightGridAligned(height);
setMeasuredDimension(getMeasuredWidth(), height);
checkMaxLines(height, MeasureSpec.getMode(heightMeasureSpec));
}
/**
* Ensures line height is a multiple of 4dp.
*/
private void computeLineHeight() {
final Paint.FontMetricsInt fm = getPaint().getFontMetricsInt();
final int fontHeight = Math.abs(fm.ascent - fm.descent) + fm.leading;
final float desiredLineHeight = (lineHeightHint > 0)
? lineHeightHint
: lineHeightMultiplierHint * fontHeight;
final int baselineAlignedLineHeight =
(int) (FOUR_DIP * (float) Math.ceil(desiredLineHeight / FOUR_DIP));
setLineSpacing(baselineAlignedLineHeight - fontHeight, 1f);
}
/**
* Ensure that the first line of text sits on the 4dp grid.
*/
private int ensureBaselineOnGrid() {
float baseline = getBaseline();
float gridAlign = baseline % FOUR_DIP;
if (gridAlign != 0) {
extraTopPadding = (int) (FOUR_DIP - Math.ceil(gridAlign));
}
return extraTopPadding;
}
/**
* Ensure that height is a multiple of 4dp.
*/
private int ensureHeightGridAligned(int height) {
float gridOverhang = height % FOUR_DIP;
if (gridOverhang != 0) {
extraBottomPadding = (int) (FOUR_DIP - Math.ceil(gridOverhang));
}
return extraBottomPadding;
}
/**
* When measured with an exact height, text can be vertically clipped mid-line. Prevent
* this by setting the {@code maxLines} property based on the available space.
*/
private void checkMaxLines(int height, int heightMode) {
if (!maxLinesByHeight || heightMode != MeasureSpec.EXACTLY) return;
int textHeight = height - getCompoundPaddingTop() - getCompoundPaddingBottom();
int completeLines = (int) Math.floor(textHeight / getLineHeight());
setMaxLines(completeLines);
}
}
還需要一個自定義屬性的xml文件,即attrs_baseline_grid_text_view.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="BaselineGridTextView">
<attr name="lineHeightMultiplierHint" format="float" />
<attr name="lineHeightHint" format="dimension"/>
<attr name="maxLinesByHeight" format="boolean" />
</declare-styleable>
</resources>
解析
理解FontMetrics
如果說FontTextView的目的很好理解的話,這個控件的目的就不是那么直白岗钩,因?yàn)榭赡芏紱]接觸過TextView的FontMetrics。既然說到Baseline阱当,那么就照搬stackOverflow上面的一個回答吧:
- Top - The maximum distance above the baseline for the tallest glyph in the font at a given text size.
- Ascent - The recommended distance above the baseline for singled spaced text.
- Descent - The recommended distance below the baseline for singled spaced text.
- Bottom - The maximum distance below the baseline for the lowest glyph in the font at a given text size.
- Leading - The recommended additional space to add between lines of text.
Note that the Baseline is what the first four are measured from. It is line which forms the base that the text sits on, even though some characters (like g, y, j, etc.) might have parts that go below the line. It is comparable to the lines you write on in a lined notebook.
Here is a picture to help visualize these things:
Remember that when drawing on a canvas in Java and Android, going down is an increase in y and going up is a decrease in y. That means that FontMetrics' top and ascent are negative numbers since they are measured from the baseline (while descent and bottom are positive numbers). Thus, to get the distance from top to bottom you would need to do (bottom - top).
The leading is the distance between the bottom of one line and the top of the next line. In the picture above, it is the space between the orange of Line 1 and the purple of Line 2. (……省略之后)
這個回答圖文并茂桃煎,比較清晰地說明了FontMetrics里面有什么東西以及代表什么意思。
之后我們就可以來學(xué)習(xí)源碼了慷嗜。
構(gòu)造函數(shù)
首先當(dāng)然從構(gòu)造器開始學(xué)。還是4個丹壕,不過這次的風(fēng)格不太一樣庆械,N個構(gòu)造參數(shù)的引用N+1個,多出的1個參數(shù)設(shè)空菌赖,然后實(shí)現(xiàn)的是4個構(gòu)造參數(shù)的構(gòu)造器缭乘。之后取出三個值,對應(yīng)的是自定義的屬性的三個值琉用,即lineHeightMultiplierHint堕绩,lineHeightHint和maxLinesByHeight策幼。至于FOUR_DIP,其實(shí)就是把4dp轉(zhuǎn)為尺寸計(jì)算可用的float值奴紧。文檔上關(guān)于applyDimension的解釋:
static float
[applyDimension](https://developer.android.com/reference/android/util/TypedValue.html#applyDimension(int, float, android.util.DisplayMetrics))(int unit, float value, DisplayMetrics metrics)
Converts an unpacked complex data value holding a dimension to its final floating point value.
computeLineHeight()
然后調(diào)用了computeLineHeight()函數(shù)特姐。看名字是計(jì)算高度的黍氮,不過看解釋是確保高度是4dp的倍數(shù)的唐含。還是看代碼。
首先利用FontMetrics來計(jì)算fontHeight沫浆,也就是字的高度捷枯,然后獲取屬性里面設(shè)置的行高,從代碼來看件缸,假如設(shè)置了lineHeightHint铜靶,則以其為準(zhǔn),否則就用lineHeightMultiplierHint他炊,這里也看出來這個值的意思就是行高是字體高度的幾倍争剿。
之后就是把設(shè)置高度轉(zhuǎn)為4dp的倍數(shù),最后再設(shè)置行間距痊末。
這里有兩個疑問:為什么fontHeight要加上leading蚕苇?為什么要用setLineSpacing方法而不用leading來設(shè)置行間距?查資料說leading貌似一般都是0凿叠,而且也一般不用這個方法來設(shè)置行間距涩笤,我也不知道具體是為什么這樣。
onMeasure
這個方法是用來確定該View及其子View的尺寸的盒件。TextView并沒有子View蹬碧,因此管好自己就行。
一上來先把兩個padding置0炒刁。然后是正常的高度測量恩沽。不過因?yàn)橐蟾叨仁?dp的倍數(shù),因此要加一些padding調(diào)整翔始,這也是設(shè)置兩個padding參數(shù)的意義罗心。從代碼知道,高度分別對頭和尾進(jìn)行了調(diào)整城瞎。
先看ensureBaselineOnGrid()渤闷,注釋是讓第一行位于4dp網(wǎng)格上。之后脖镀,為了讓計(jì)算更具體飒箭,假設(shè)baseline是15dp,gridAlign就是3dp,extraTopPadding也就是1dp补憾。說明這個extraTopPadding就是為了讓baseline是4dp的倍數(shù)而設(shè)計(jì)的漫萄。
ensureHeightGridAligned類似,不過對象是height盈匾。
最后還有一個checkMaxLines,按照注釋所說毕骡,是為了解決一個bug而自己手動setMaxLines削饵。maxLinesByHeight就在這里使用了,意思就是是不是按照高度來決定最大行數(shù)未巫。至于heightMode就關(guān)系到MeasureSpec的三種模式:EXACTLY窿撬,UNSPECIFIED和AT_MOST。其實(shí)都好理解叙凡,EXACTLY就是指定了某個值劈伴,UNSPECIFIED就是不確定,例如ScrollView對其子View的高度就沒有什么限制握爷,而AT_MOST就是有個上限跛璧。還是參考stackOverflow上的回答:
onMeasure() is your opportunity to tell Android how big you want your custom view to be dependent the layout constraints provided by the parent; it is also your custom view's opportunity to learn what those layout constraints are (in case you want to behave differently in a match_parent situation than a wrap_content situation). These constraints are packaged up into the MeasureSpec values that are passed into the method. Here is a rough correlation of the mode values:
- EXACTLY means the layout_width or layout_height value was set to a specific value. You should probably make your view this size. This can also get triggered when match_parent is used, to set the size exactly to the parent view (this is layout dependent in the framework).
- AT_MOST typically means the layout_width or layout_height value was set to match_parent or wrap_content where a maximum size is needed (this is layout dependent in the framework), and the size of the parent dimension is the value. You should not be any larger than this size.
- UNSPECIFIED typically means the layout_width or layout_height value was set to wrap_content with no restrictions. You can be whatever size you would like. Some layouts also use this callback to figure out your desired size before determine what specs to actually pass you again in a second measure request.
The contract that exists with onMeasure() is that setMeasuredDimension() MUST be called at the end with the size you would like the view to be. This method is called by all the framework implementations, including the default implementation found in View, which is why it is safe to call super instead if that fits your use case.
Granted, because the framework does apply a default implementation, it may not be necessary for you to override this method, but you may see clipping in cases where the view space is smaller than your content if you do not, and if you lay out your custom view with wrap_content in both directions, your view may not show up at all because the framework doesn't know how large it is!
小結(jié)
大公司就是大公司,精益求精新啼,為了搞一個對齊都能寫一個自定義控件追城。
我自己也試了一下這個控件,總的來說就是間距有非常微妙的差別燥撞,但很不明顯座柱。
如上圖,一共三個view物舒,第一個是普通的TextView色洞,后面兩個長的分別是FontTextView和BaselineGridTextView。通過觀察不難看出冠胯,確實(shí)是行間距變了火诸。沒有影響橫向的對齊。
<FontTextView
android:id="@+id/tv_2"
android:layout_below="@+id/tv_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/long_text"
app:font="roboto-mono-regular"
android:textSize="14sp"/>
<BaselineGridTextView
android:id="@+id/tv_3"
android:layout_below="@+id/tv_2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/long_text"
app:font="roboto-mono-regular"
app:lineHeightHint="24sp"/>
此外涵叮,BaselineGridTextView可以直接設(shè)置行高度而無需再設(shè)置textSize惭蹂,在某些時候也會很方便。