当前位置:网站首页>The drawableleft of the custom textview in kotlin is displayed in the center together with the text

The drawableleft of the custom textview in kotlin is displayed in the center together with the text

2022-06-25 00:21:00 BY-91


import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.widget.TextView


/**
* Author: yangtianfu
* Date: 2021/1/25 18:08
* Describe:drawableLeft Center with text 
*/
@SuppressLint("AppCompatCustomView")
class DrawableCenterTextView : TextView {
    constructor(
        context: Context?, attrs: AttributeSet?,
        defStyle: Int
    ) : super(context, attrs, defStyle){}

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {}
    constructor(context: Context?) : super(context) {}

    override fun onDraw(canvas: Canvas) {
        val drawables = compoundDrawables
        if (drawables != null) {
            val drawableLeft = drawables[0]
            if (drawableLeft != null) {
                val textWidth = paint.measureText(text.toString())
                val drawablePadding = compoundDrawablePadding
                var drawableWidth =  drawableLeft.intrinsicWidth
                val bodyWidth = textWidth + drawableWidth + drawablePadding
                canvas.translate((width - bodyWidth) / 2, 0F)
            }
        }
        super.onDraw(canvas)
    }
}

Use

<DrawableCenterTextView
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:gravity="center_vertical"
                android:text=" contact "
                android:drawablePadding="8dp"
                android:drawableLeft="@drawable/icon_call"
                android:textColor="#ff000000"
                android:textSize="14sp"/>
原网站

版权声明
本文为[BY-91]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202210550382827.html