import android.annotation.SuppressLintimport android.content.Contextimport android.graphics.Canvasimport android.util.AttributeSetimport android.widget.TextView/*** Author: yangtianfu* Date: /1/25 18:08* Describe:drawableLeft与文本一起居中显示*/@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 = compoundDrawablesif (drawables != null) {val drawableLeft = drawables[0]if (drawableLeft != null) {val textWidth = paint.measureText(text.toString())val drawablePadding = compoundDrawablePaddingvar drawableWidth = drawableLeft.intrinsicWidthval bodyWidth = textWidth + drawableWidth + drawablePaddingcanvas.translate((width - bodyWidth) / 2, 0F)}}super.onDraw(canvas)}}
使用
<DrawableCenterTextViewandroid:layout_width="0dp"android:layout_height="match_parent"android:layout_weight="1"android:gravity="center_vertical"android:text="联系"android:drawablePadding="8dp"android:drawableLeft="@drawable/icon_call"android:textColor="#ff000000"android:textSize="14sp"/>