返回
自定义TextView之drawableLeft与文本一起居中显示
Android
2024-01-10 14:03:08
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.TextView;
/**
* 自定义TextView,实现drawableLeft与文本一起居中显示
*/
public class DrawableCenterTextView extends TextView {
private Drawable drawableLeft; // 左侧图片
private int drawableWidth; // 左侧图片的宽度
private int drawableHeight; // 左侧图片的高度
private int textWidth; // 文本的宽度
private int textHeight; // 文本的高度
private int totalWidth; // 总宽度
private int totalHeight; // 总高度
public DrawableCenterTextView(Context context) {
super(context);
init();
}
public DrawableCenterTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public DrawableCenterTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
// 获取左侧图片
drawableLeft = getCompoundDrawables()[0];
if (drawableLeft != null) {
// 获取左侧图片的宽高
drawableWidth = drawableLeft.getIntrinsicWidth();
drawableHeight = drawableLeft.getIntrinsicHeight();
}
// 获取文本的宽高
textWidth = (int) getPaint().measureText(getText().toString());
textHeight = (int) getPaint().getTextSize();
// 计算总宽度和总高度
totalWidth = drawableWidth + textWidth + getCompoundDrawablePadding();
totalHeight = Math.max(drawableHeight, textHeight);
}
@Override
protected void onDraw(Canvas canvas) {
// 绘制左侧图片
if (drawableLeft != null) {
int left = (totalWidth - drawableWidth) / 2;
int top = (totalHeight - drawableHeight) / 2;
drawableLeft.setBounds(left, top, left + drawableWidth, top + drawableHeight);
drawableLeft.draw(canvas);
}
// 绘制文本
Paint paint = getPaint();
paint.setColor(getCurrentTextColor());
int left = (totalWidth - textWidth) / 2;
int baseline = (totalHeight - textHeight) / 2 + textHeight;
canvas.drawText(getText().toString(), left, baseline, paint);
}
@SuppressLint("DrawAllocation")
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
// 计算控件的宽高
int width;
int height;
if (widthMode == MeasureSpec.EXACTLY) {
width = widthSize;
} else {
width = totalWidth;
}
if (heightMode == MeasureSpec.EXACTLY) {
height = heightSize;
} else {
height = totalHeight;
}
setMeasuredDimension(width, height);
}
/**
* 设置左侧图片
*
* @param drawableLeft 左侧图片
*/
public void setDrawableLeft(Drawable drawableLeft) {
this.drawableLeft = drawableLeft;
init();
invalidate(); // 重新绘制控件
}
/**
* 获取左侧图片
*
* @return 左侧图片
*/
public Drawable getDrawableLeft() {
return drawableLeft;
}
}
自定义TextView,实现drawableLeft与文本一起居中显示,可应用于各种自定义控件场景。