How to remove the top and bottom space on textview of Android

前端 未结 14 1981
执笔经年
执笔经年 2020-11-28 04:58

When I include the below XML to layout file, I can see the below image. If you see it, you could realize that the TextView has top and bot

14条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 05:40

    Modified this answer a little bit to use kotlin class and extend AppCompatTextView, trimming vertical padding.

    It allows setting android:fontFamily. Method calculateTextParams() moved from onDraw() for performance. Not tested for multiple lines of text:

    import android.content.Context
    import android.graphics.Canvas
    import android.graphics.Rect
    import android.util.AttributeSet
    import androidx.appcompat.widget.AppCompatTextView
    
    class NoPaddingTextView : AppCompatTextView
    {
      private val boundsRect = Rect()
      private val textParams = calculateTextParams()
    
      constructor(context : Context?)
      : super(context)
    
      constructor(context : Context?, attrs : AttributeSet?)
      : super(context, attrs)
    
      constructor(context : Context?, attrs : AttributeSet?, defStyleAttr : Int)
      : super(context, attrs, defStyleAttr)
    
      override fun onDraw(canvas : Canvas)
      {
        with(boundsRect) {
          paint.isAntiAlias = true
          paint.color = currentTextColor
          canvas.drawText(textParams,
                          -left.toFloat(),
                          (-top - bottom).toFloat(),
                          paint)
        }
      }
    
      override fun onMeasure(widthMeasureSpec : Int, heightMeasureSpec : Int)
      {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        calculateTextParams()
        setMeasuredDimension(boundsRect.width() + 1, -boundsRect.top + 1)
      }
    
      private fun calculateTextParams() : String
      {
        return text.toString()
        .also {text ->
          text.length.let {textLength ->
            paint.textSize = textSize
            paint.getTextBounds(text, 0, textLength, boundsRect)
            if(textLength == 0) boundsRect.right = boundsRect.left
          }
        }
      }
    }
    

提交回复
热议问题