Why does TextView have end padding when multi line?

前端 未结 4 782
执念已碎
执念已碎 2021-02-07 06:27

If you have a TextView with layout_width=\"wrap_content\" and it has to wrap to a second line to contain the text, then it will size its width to use up all of the

4条回答
  •  情书的邮戳
    2021-02-07 07:12

    I recently faced a similar problem when developing a chat-bubble view for an app, so I used the ideas from the accepted solution, and @hoffware's improvements, and re-implemented them in Kotlin.

    import android.content.Context
    import android.util.AttributeSet
    import android.view.View.MeasureSpec.*
    import androidx.appcompat.widget.AppCompatTextView
    import kotlin.math.ceil
    
    class TightTextView
    @JvmOverloads constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyleAttr: Int = android.R.attr.textViewStyle
    ) : AppCompatTextView(context, attrs, defStyleAttr) {
    
        override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    
            val lineCount = layout.lineCount
            if (lineCount > 1 && getMode(widthMeasureSpec) != EXACTLY) {
                val textWidth = (0 until lineCount).maxOf(layout::getLineWidth)
                val padding = compoundPaddingLeft + compoundPaddingRight
                val w = ceil(textWidth).toInt() + padding
    
                if (w < measuredWidth) {
                    val newWidthMeasureSpec = makeMeasureSpec(w, AT_MOST)
                    super.onMeasure(newWidthMeasureSpec, heightMeasureSpec)
                }
            }
        }
    }
    

提交回复
热议问题