Keep text in TextView with drawableLeft centered

后端 未结 21 1243
野的像风
野的像风 2021-02-03 17:10

In my app I have a header bar which consists of a single textview with fill_parent as width, which have a specific background color and some centered text. Now I want to add a d

21条回答
  •  时光取名叫无心
    2021-02-03 17:50

    no test too much, another way

        class CenterDrawableToggleButton @JvmOverloads constructor(
            context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
        ) : AppCompatToggleButton(context, attrs, defStyleAttr) {
    
            private val centerMatrix = Matrix()
    
            override fun onDraw(canvas: Canvas?) {
                canvas?.save()?:return
                centerMatrix.reset()
                centerMatrix.postTranslate(width / 2F - (getDrawWidth() / 2), 0F)
                canvas.concat(centerMatrix)
                super.onDraw(canvas)
                canvas.restore()
            }
    
            private fun getDrawWidth(): Float {
                return paint.measureText(text.toString()) + compoundPaddingRight + compoundPaddingLeft
            }
        }
    

提交回复
热议问题