100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > kotlin中自定义TextView之drawableLeft与文本一起居中显示

kotlin中自定义TextView之drawableLeft与文本一起居中显示

时间:2021-06-01 18:04:31

相关推荐

kotlin中自定义TextView之drawableLeft与文本一起居中显示

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"/>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。