欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

TextView文本和DrawableStart居中显示

程序员文章站 2024-01-16 22:11:28
一.本文实现的效果是TextView包裹的图标和Text一起居中显示,且TextView的宽度为match_content,效果如图所示:二.附自定义TextView代码:import android.content.Context;import android.graphics.Canvas;import android.graphics.drawable.Drawable;import android.text.Layout;import android.util.AttributeSet...

一.本文实现的效果是TextView包裹的图标和Text一起居中显示,且TextView的宽度为match_content,效果如图所示:

TextView文本和DrawableStart居中显示

二.附自定义TextView代码:

import android.content.Context; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.text.Layout; import android.util.AttributeSet; import androidx.appcompat.widget.AppCompatTextView; public class DrawableCenterTextView extends AppCompatTextView { public DrawableCenterTextView(Context context, AttributeSet attrs,int defStyle) { super(context, attrs, defStyle); } public DrawableCenterTextView(Context context, AttributeSet attrs) { super(context, attrs); } public DrawableCenterTextView(Context context) { super(context); } @Override protected void onDraw(Canvas canvas) { // We want the icon and/or text grouped together and centered as a group. // We need to accommodate any existing padding final float buttonContentWidth = getWidth() - getPaddingLeft() - getPaddingRight(); float textWidth = 0f; final Layout layout = getLayout(); if (layout != null) { for (int i = 0; i < layout.getLineCount(); i++) { textWidth = Math.max(textWidth, layout.getLineRight(i)); } } // Compute left drawable width, if any Drawable[] drawables = getCompoundDrawables(); Drawable drawableLeft = drawables[0]; int drawableWidth = (drawableLeft != null) ? drawableLeft.getIntrinsicWidth() : 0; // We only count the drawable padding if there is both an icon and text int drawablePadding = ((textWidth > 0) && (drawableLeft != null)) ? getCompoundDrawablePadding() : 0; // Adjust contents to center float bodyWidth = textWidth + drawableWidth + drawablePadding; int translate = (int) ((buttonContentWidth - bodyWidth)); if (translate != 0) setPadding(translate, 0, translate, 0); //        canvas.translate((buttonContentWidth - bodyWidth) / 2, 0); super.onDraw(canvas); } } 

三.xml中使用方法:

com.*.DrawableCenterTextView请替换成自己的实际包名

 <com.*.DrawableCenterTextView android:id="@+id/tv_add_scene" android:layout_width="0dp" android:layout_height="63dp" android:layout_gravity="center" android:layout_weight="1" android:background="@drawable/drawable_edit_btn" android:drawableStart="@drawable/icon_add_item_green" android:drawablePadding="15dp" android:gravity="center" android:text="添加场景" android:textColor="#333333" android:textSize="14sp" /> 

本文地址:https://blog.csdn.net/cyfxiaochen/article/details/107766815