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;
  }
}

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

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。