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


轉載請標明出處:https://www.cnblogs.com/tangZH/p/11985745.html

更多精彩文章:http://77blogs.com/?p=278

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

可以用下面這種方法解決:

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;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM