这篇文章给大家分享的是有关Android如何自定义TextView去除paddingTop和paddingBottom的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
Android 自定义TextView去除paddingTop和paddingBottom
最近项目中需要用libgdx渲染一个Android的TextView, 但是绘制出来的TextView总是默认带有paddingTop和paddingBottom, 如下图所示:
网上有很多解决方案,例如在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;
}
}
感谢各位的阅读!关于“Android如何自定义TextView去除paddingTop和paddingBottom”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。