欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2023-02-05 18:10:32
转载请标明出处:https://www.cnblogs.com/tangZH/p/11985745.html 有些手机中,给TextView设置lineSpacingExtra后会出现最后一行的文字也出现lineSpacingExtra,不是某些版本才会,这跟机型有关。 可以用下面这种方法解决: ......

转载请标明出处:https://www.cnblogs.com/tangzh/p/11985745.html

有些手机中,给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;
    }
}