网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

Android如何自定义TextView去除paddingTop和paddingBottom

这篇文章给大家分享的是有关Android如何自定义TextView去除paddingTop和paddingBottom的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

创新互联建站主营青神网站建设的网络公司,主营网站建设方案,app软件定制开发,青神h5微信小程序开发搭建,青神网站营销推广欢迎青神等地区企业咨询

Android 自定义TextView去除paddingTop和paddingBottom

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

Android如何自定义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”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!


网站名称:Android如何自定义TextView去除paddingTop和paddingBottom
标题网址:http://bjjierui.cn/article/ipposc.html

其他资讯