自定义控件让TextView的drawableLeft与文本一起居中显示
在实际开发中,有时需要在TextView的左边或者右边显示一张图片,我们会是用drawableLeft(drawableRight)属性来设置图片
或者嵌套布局来实现,嵌套布局有一点不好就是增加了view的层级,影响性能,而设置drawableLeft属性也有个限制,import android.content.Context; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.widget.TextView; /** * 自定义控件让TextView的drawableLeft或者drawableRight与文本一起居中显示 */ public class DrawableCenterTextView extends TextView { public DrawableCenterTextView(Context context) { this(context,null); } public DrawableCenterTextView(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onDraw(Canvas canvas) { Drawable[] drawables = getCompoundDrawables(); if(drawables != null){ Drawable leftDrawable = drawables[0]; //drawableLeft Drawable rightDrawable = drawables[2];//drawableRight if(leftDrawable !=null || rightDrawable != null){ //1,获取text的width float textWidth = getPaint().measureText(getText().toString()); //2,获取padding int drawablePadding = getCompoundDrawablePadding(); int drawableWidth; float bodyWidth; if(leftDrawable !=null){ //3,获取drawable的宽度 drawableWidth = leftDrawable.getIntrinsicWidth(); //4,获取绘制区域的总宽度 bodyWidth= textWidth + drawablePadding + drawableWidth; }else{ drawableWidth = rightDrawable.getIntrinsicWidth(); bodyWidth= textWidth + drawablePadding + drawableWidth; //图片居右设置padding setPadding(0, 0, (int)(getWidth() - bodyWidth), 0); } canvas.translate((getWidth() - bodyWidth)/2,0); } } super.onDraw(canvas); } }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <ihuayue.com.drawableleftdemo.DrawableCenterTextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_vertical" android:background="@android:color/holo_blue_bright" android:drawableRight="@mipmap/ic_launcher" android:drawablePadding="10dp" android:text="Hello World!"/> </LinearLayout>
和普通TextView用法一致,这样既可以让我们的控件大小是match_parent或者固定大小的,又能使图片和文字居中了
资料来源:http://www.cnblogs.com/over140/p/3464348.html