原理参考: https://blog.csdn.net/harvic880925/article/details/50423762
通过自己设置控件删除上下内边距, UI走查时就不用担心间距不对了。
代码:
public class MyTextView extends TextView { public MyTextView(Context context) { super(context); } public MyTextView(Context context, AttributeSet attrs) { super(context, attrs); setGravity(getGravity() | Gravity.CENTER_VERTICAL); setIncludeFontPadding(false); } public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onDraw(Canvas canvas) { Paint.FontMetrics fm = getPaint().getFontMetrics(); if (fm != null) { if (getScrollY() != (int)(fm.ascent-fm.top)) { setScrollY((int) (fm.ascent - fm.top)); } } super.onDraw(canvas); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int padding = 0; Paint.FontMetrics fm = getPaint().getFontMetrics(); if (fm != null) { padding = (int) Math.abs(fm.top - fm.ascent) + (int) Math.abs(fm.bottom - fm.descent); int width = getMeasuredWidth(); int heiht = getMeasuredHeight(); if (getText().toString().contains("g") || getText().toString().contains("y") || getText().toString().contains("p")) { setMeasuredDimension(width, heiht - padding); } else { setMeasuredDimension(width, heiht - padding - (int)(getTextSize()*0.1)); } } }
缺陷:
由于无法判断TextView的字符下边界能否超过其它字符, 假如都是中文就没问题。 但p、q、g等字符下边界比较低, 这类字符需要单独判断, 可能会漏掉少量字符。