Make a certain part of a android-textview align to the right

前端 未结 6 1461
南旧
南旧 2020-12-04 20:37

I have this TextView. Some parts of it is supposed to be aligned to the left and some parts to the right. How would I do this in Java?

Basicly I want t

6条回答
  •  情话喂你
    2020-12-04 20:43

    Inspired other solutions, but resolving multiline text issues and text overlap issue.

    class LineOverlapSpan() : LineHeightSpan {
        var originalBottom: Int = 0
        var originalDescent: Int = 0
        var overlapSaved = false
    
        override fun chooseHeight(
            text: CharSequence?,
            start: Int,
            end: Int,
            spanstartv: Int,
            v: Int,
            fm: Paint.FontMetricsInt?
        ) {
            if (fm == null) {
                return
            }
    
            if (!overlapSaved) {
                originalBottom = fm.bottom
                originalDescent = fm.descent
                overlapSaved = true
            }
    
            if (text?.subSequence(start, end)?.endsWith("\n") == true) {
                fm.bottom += fm.top
                fm.descent += fm.top
            } else {
                fm.bottom = originalBottom
                fm.descent = originalDescent
            }
        }
    
    }
    

    Usage:

    fun keyValueSpan(key: CharSequence, value: CharSequence) = span {
        span {
            alignment = "normal"
            +key
            span {
                textColor = Color.TRANSPARENT
                +value
            }
            span {
                +"\n"
                addSpan(LineOverlapSpan())
            }
        }
        span {
            alignment = "opposite"
            +value
        }
    }
    

    Kotlin solution is using Kpan library https://github.com/2dxgujun/Kpan

提交回复
热议问题