Android 自定义TextView去除paddingTop和paddingBottom
程序员文章站
2023-12-19 10:15:28
android 自定义textview去除paddingtop和paddingbottom
最近项目中需要用libgdx渲染一个android的textview, 但是绘...
android 自定义textview去除paddingtop和paddingbottom
最近项目中需要用libgdx渲染一个android的textview, 但是绘制出来的textview总是默认带有paddingtop和paddingbottom, 如下图所示:
网上有很多解决方案,例如在xml中设置如下属性:
android:linespacingmultiplier="0.8" android:includefontpadding="false"
或者设置margin为负值等等。 但是以上方法在6.0之后都没什么卵用。
只有一种方法可以做到,就是自定义textview
package com.ef.smallstar.common.widget; import android.content.context; import android.graphics.canvas; import android.graphics.paint; import android.graphics.rect; import android.support.annotation.nonnull; import android.util.attributeset; /** * created by danny on 17/8/28. * * this is a android textview without padding top & padding bottom */ public class textviewwithoutpadding extends android.support.v7.widget.appcompattextview { private final paint mpaint = new paint(); private final rect mbounds = new rect(); public textviewwithoutpadding(context context) { super(context); } public textviewwithoutpadding(context context, attributeset attrs) { super(context, attrs); } public textviewwithoutpadding(context context, attributeset attrs, int defstyleattr) { super(context, attrs, defstyleattr); } @override protected void ondraw(@nonnull canvas canvas) { final string text = calculatetextparams(); final int left = mbounds.left; final int bottom = mbounds.bottom; mbounds.offset(-mbounds.left, -mbounds.top); mpaint.setantialias(true); mpaint.setcolor(getcurrenttextcolor()); canvas.drawtext(text, -left, mbounds.bottom - bottom, mpaint); } @override protected void onmeasure(int widthmeasurespec, int heightmeasurespec) { super.onmeasure(widthmeasurespec, heightmeasurespec); calculatetextparams(); setmeasureddimension(mbounds.width() + 1, -mbounds.top + 1); } private string calculatetextparams() { final string text = gettext().tostring(); final int textlength = text.length(); mpaint.settextsize(gettextsize()); mpaint.gettextbounds(text, 0, textlength, mbounds); if (textlength == 0) { mbounds.right = mbounds.left; } return text; } }
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!