Android 사용자 정의 TextView padding Top 과 padding Bottom 제거

2836 단어 AndroidTextView
Android 사용자 정의 TextView padding Top 과 padding Bottom 제거
최근 프로젝트 에 서 는 libgdx 로 안 드 로 이 드 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;
  }
}

궁금 한 점 이 있 으 시 면 메 시 지 를 남기 거나 본 사이트 의 커 뮤 니 티 에 가서 토론 을 교류 하 세 요.읽 어 주 셔 서 감사합니다. 도움 이 되 셨 으 면 좋 겠 습 니 다.본 사이트 에 대한 지지 에 감 사 드 립 니 다!

좋은 웹페이지 즐겨찾기