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); } }
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
如对本文有疑问, 点击进行留言回复!!
Android进程通信(AIDL快速实现inder进程通信)
Android开发使用SimpleAdapter与ListView列表展示增加头和尾
Execution failed for task ‘:app:checkDebugDuplicateClasses‘解决方案
Cleartext HTTP traffic to pic1.win4000.com not permitted不允许明文http访问解决
Android SDK 26以后ant编译错误解决办法(错误信息:taskdef A class needed by class com.android.ant.GetUiTargetTask)
android8.1 mtk camera hal各种操作流程
Android 软键盘在有scollview,纵向viewpager+recyclview实现列表,或者recyclview, 把布局顶上去的问题,保证背景不会发生变化
网友评论