android自定义textview销毁,Android自定义View去除TextView的Padding值

在业务中需要对齐一个大字体和小字体

方案一:利用ImageView也可以实现这个对齐效果,但是如果同比例缩放的话,它们之间的间距会被拉开,不美观了。

方案二:可以利用TextViewWithoutPaddings,这种对齐方式对得很齐,还有一个优点就是同比例缩放的时候后,同样可以对得很齐。

以下是代码和效果图:

/**

* Created by lilea on 2017/7/31.

*/

public class TextViewWithoutPaddings extends TextView {

private final Paint mPaint = new Paint();

private final Rect mBounds = new Rect();

public TextViewWithoutPaddings(Context context) {

super(context);

}

public TextViewWithoutPaddings(Context context, @Nullable AttributeSet attrs) {

super(context, attrs);

}

public TextViewWithoutPaddings(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {

super(context, attrs, defStyleAttr);

}

public TextViewWithoutPaddings(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {

super(context, attrs, defStyleAttr, defStyleRes);

}

@Override

protected void onDraw(@NonNull Canvas canvas) {

final String text = calculateTextParams();

final int left = mBounds.left;

final int bottom = mBounds.bottom;

mBounds.offset(-mBounds.left, -mBounds.top);

mPaint.setAntiAlias(true);

mPaint.setColor(getCurrentTextColor());

canvas.drawText(text, -left, mBounds.bottom - bottom, mPaint);

}

@Override

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

super.onMeasure(widthMeasureSpec, heightMeasureSpec);

calculateTextParams();

setMeasuredDimension(mBounds.right - mBounds.left, -mBounds.top + mBounds.bottom);

}

private String calculateTextParams() {

final String text = getText().toString();

final int textLength = text.length();

mPaint.setTextSize(getTextSize());

mPaint.getTextBounds(text, 0, textLength, mBounds);

if (textLength == 0) {

mBounds.right = mBounds.left;

}

return text;

}

}

用法直接用TextView继承该view,在布局文件中替换TextView即可。

图一

a7a69338eaecc11d8c80d3a412d52634.png

图二

b9f1f1396eb8c8741cbedbc84d8121ab.png

图一是去除padding值的效果(TextViewWithoutPaddings ),图二是直接利用TextView。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值