You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中TextView高度大于文本高度且padding设0仍有间距的原因?

解决TextView自带多余内边距的问题

你遇到的不是TextView的padding问题,而是字体本身的行高和默认内边距导致的空白,即使设置padding="0dp"也无法消除。可以通过以下几种方法解决:

1. 关闭字体默认内边距

添加android:includeFontPadding="false"属性,这个属性会移除Android为字体预留的默认上下内边距,是最直接的解决方式:

<TextView 
    android:id="@+id/textViewSpeed" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="test" 
    android:textColor="@color/black" 
    android:fontFamily="monospace" 
    android:textSize="150sp"  
    android:padding="0dp"
    android:includeFontPadding="false"/>

2. 强制行高与字号一致

如果关闭字体内边距后还有剩余空白,可以手动设置lineHeight和字号相同,强制压缩行高:

<TextView 
    android:id="@+id/textViewSpeed" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="test" 
    android:textColor="@color/black" 
    android:fontFamily="monospace" 
    android:textSize="150sp"  
    android:padding="0dp"
    android:includeFontPadding="false"
    android:lineHeight="150sp"/>

根据实际显示效果,lineHeight可以微调(比如设为145sp),直到空白消失。

3. 自定义TextView精确适配

如果以上方法都达不到要求,可以自定义TextView,直接根据文本的实际高度计算控件高度:

class TightTextView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr) {

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val paint = paint
        val text = text ?: return
        val textBounds = Rect()
        paint.getTextBounds(text.toString(), 0, text.length, textBounds)
        // 用文本实际高度替换默认测量高度
        setMeasuredDimension(measuredWidth, textBounds.bottom - textBounds.top)
    }
}

在布局中使用这个自定义View即可让控件高度完全贴合文本内容。

内容的提问来源于stack exchange,提问作者ronenfe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 19:12:42