源码
BaselineGridTextView是继承FontTextView的一个自定义控件:
/**
* An extension to {@link android.widget.TextView} which aligns text to a 4dp baseline grid.
*
* 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.
*
* 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:
解析
理解FontMetrics
如果说FontTextView的目的很好理解的话,这个控件的目的就不是那么直白,因为可能都没接触过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里面有什么东西以及代表什么意思。
之后我们就可以来学习源码了。
构造函数
首先当然从构造器开始学。还是4个,不过这次的风格不太一样,N个构造参数的引用N+1个,多出的1个参数设空,然后实现的是4个构造参数的构造器。之后取出三个值,对应的是自定义的属性的三个值,即lineHeightMultiplierHint,lineHeightHint和maxLinesByHeight。至于FOUR_DIP,其实就是把4dp转为尺寸计算可用的float值。文档上关于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()
然后调用了computeLineHeight()函数。看名字是计算高度的,不过看解释是确保高度是4dp的倍数的。还是看代码。
首先利用FontMetrics来计算fontHeight,也就是字的高度,然后获取属性里面设置的行高,从代码来看,假如设置了lineHeightHint,则以其为准,否则就用lineHeightMultiplierHint,这里也看出来这个值的意思就是行高是字体高度的几倍。
之后就是把设置高度转为4dp的倍数,最后再设置行间距。
这里有两个疑问:为什么fontHeight要加上leading?为什么要用setLineSpacing方法而不用leading来设置行间距?查资料说leading貌似一般都是0,而且也一般不用这个方法来设置行间距,我也不知道具体是为什么这样。
onMeasure
这个方法是用来确定该View及其子View的尺寸的。TextView并没有子View,因此管好自己就行。
一上来先把两个padding置0。然后是正常的高度测量。不过因为要求高度是4dp的倍数,因此要加一些padding调整,这也是设置两个padding参数的意义。从代码知道,高度分别对头和尾进行了调整。
先看ensureBaselineOnGrid(),注释是让第一行位于4dp网格上。之后,为了让计算更具体,假设baseline是15dp,gridAlign就是3dp,extraTopPadding也就是1dp。说明这个extraTopPadding就是为了让baseline是4dp的倍数而设计的。
ensureHeightGridAligned类似,不过对象是height。
最后还有一个checkMaxLines,按照注释所说,是为了解决一个bug而自己手动setMaxLines。maxLinesByHeight就在这里使用了,意思就是是不是按照高度来决定最大行数。至于heightMode就关系到MeasureSpec的三种模式:EXACTLY,UNSPECIFIED和AT_MOST。其实都好理解,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!
小结
大公司就是大公司,精益求精,为了搞一个对齐都能写一个自定义控件。
我自己也试了一下这个控件,总的来说就是间距有非常微妙的差别,但很不明显。
如上图,一共三个view,第一个是普通的TextView,后面两个长的分别是FontTextView和BaselineGridTextView。通过观察不难看出,确实是行间距变了。没有影响横向的对齐。
此外,BaselineGridTextView可以直接设置行高度而无需再设置textSize,在某些时候也会很方便。