去除TextView設置lineSpacingExtra後,最後一行多出的空白

轉載請標明出處:http://www.javashuo.com/article/p-xkvwwtfw-n.htmlhtml

有些手機中,給TextView設置lineSpacingExtra後會出現最後一行的文字也出現lineSpacingExtra,不是某些版本纔會,這跟機型有關。spa

能夠用下面這種方法解決:code

public class LastLineNoSpaceTextView extends AppCompatTextView {
    private Rect mRect;

    public LastLineNoSpaceTextView(Context context) {
        super(context);
        init();
    }

    public LastLineNoSpaceTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public LastLineNoSpaceTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mRect = new Rect();
    }

    protected void onMeasure(int i, int i2) {
        super.onMeasure(i, i2);
        int measuredHeight = getMeasuredHeight() - getLastLineSpace();
        setMeasuredDimension(getMeasuredWidth(), measuredHeight);
    }

    public int getLastLineSpace() {
        int lastLineIndex = getLineCount() - 1;
        if (lastLineIndex < 0) {
            return 0;
        }
        Layout layout = getLayout();
        int baseline = getLineBounds(lastLineIndex, mRect);
        if (getMeasuredHeight() - getPaddingTop() - getPaddingBottom() != layout.getHeight()) {
            return 0;
        }
        int fontHeight = baseline + layout.getPaint().getFontMetricsInt().descent;
        int lineHeight = mRect.bottom;
        return lineHeight - fontHeight;
    }
}
相關文章
相關標籤/搜索