背景:产品姐姐需要吧¥符号和123456785价格等text内容的内边距去掉。
NumberTextView代码:
package com.devleo.text.demo;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;
/**
* @author DevleoDeng
*/
public class NumberTextView extends AppCompatTextView {
private Rect mRect;
public NumberTextView(Context context) {
super(context);
}
public NumberTextView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public NumberTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (mRect == null) {
//该坐标是以(0,0)为基准的矩形坐标
mRect = new Rect();
}
getPaint().getTextBounds(getText().toString(), 0, getText().length(), mRect);
final int width = mRect.width();
final int height = mRect.height();
setMeasuredDimension(width, height);
}
@Override
protected void onDraw(Canvas canvas) {
final String text = getText().toString();
final int left = mRect.left;
final int top = mRect.top;
Paint paint = getPaint();
paint.setColor(getCurrentTextColor());
canvas.drawText(text, -left, -top, paint);
}
}