前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Android 自定义TextView去除paddingTop和paddingBottom

Android 自定义TextView去除paddingTop和paddingBottom

作者头像
砸漏
发布2020-10-22 11:28:44
8110
发布2020-10-22 11:28:44
举报
文章被收录于专栏:恩蓝脚本恩蓝脚本

Android 自定义TextView去除paddingTop和paddingBottom

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

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

代码语言:javascript
复制
android:lineSpacingMultiplier="0.8"
android:includeFontPadding="false"

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

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

代码语言:javascript
复制
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;
  }
}

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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-09-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档