android自定义textview销毁,Android 自定义TextView去除paddingTop和paddingBottom

Android 自定义TextView去除paddingTop和paddingBottom

最近项目中需要用libgdx渲染一个Android的TextView, 但是绘制出来的TextView总是默认带有paddingTop和paddingBottom, 如下图所示:

4812f5abd5f14b2ddf51105f1699625b.png

网上有很多解决方案,例如在xml中设置如下属性:

android:lineSpacingMultiplier="0.8"

android:includeFontPadding="false"

或者设置margin为负值等等。 但是以上方法在6.0之后都没什么卵用。

只有一种方法可以做到,就是自定义TextView

package com.ef.smallstar.common.widget;

import android.content.Context;

import android.graphics.Canvas;

import android.graphics.Paint;

import android.graphics.Rect;

import android.support.annotation.NonNull;

import android.util.AttributeSet;

/**

* Created by Danny on 17/8/28.

*

* this is a Android TextView without padding top & padding bottom

*/

public class TextViewWithoutPadding extends android.support.v7.widget.AppCompatTextView {

private final Paint mPaint = new Paint();

private final Rect mBounds = new Rect();

public TextViewWithoutPadding(Context context) {

super(context);

}

public TextViewWithoutPadding(Context context, AttributeSet attrs) {

super(context, attrs);

}

public TextViewWithoutPadding(Context context, AttributeSet attrs, int defStyleAttr) {

super(context, attrs, defStyleAttr);

}

@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.width() + 1, -mBounds.top + 1);

}

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;

}

}

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值