刪除TextView上下內邊距

原理參考: https://blog.csdn.net/harvic880925/article/details/50423762

通過自定義控件刪除上下內邊距, UI走查時就不用擔心間距不對了。
在這裏插入圖片描述

代碼:

public class MyTextView extends TextView {

  public MyTextView(Context context) {
    super(context);
  }

  public MyTextView(Context context, AttributeSet attrs) {
    super(context, attrs);

    setGravity(getGravity() | Gravity.CENTER_VERTICAL);
    setIncludeFontPadding(false);
  }

  public MyTextView(Context context,  AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
  }

  @Override protected void onDraw(Canvas canvas) {
    Paint.FontMetrics fm = getPaint().getFontMetrics();
    if (fm != null) {
      if (getScrollY() != (int)(fm.ascent-fm.top)) {
        setScrollY((int) (fm.ascent - fm.top));
      }
    }

    super.onDraw(canvas);
  }

  @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int padding = 0;
    Paint.FontMetrics fm = getPaint().getFontMetrics();
    if (fm != null) {
      padding = (int) Math.abs(fm.top - fm.ascent) + (int) Math.abs(fm.bottom - fm.descent);
      int width = getMeasuredWidth();
      int heiht = getMeasuredHeight();

      if (getText().toString().contains("g")
           || getText().toString().contains("y")
           || getText().toString().contains("p")) {
        setMeasuredDimension(width, heiht - padding);
      } else {
        setMeasuredDimension(width, heiht - padding - (int)(getTextSize()*0.1));
      }
    }
  }

缺陷:
因爲無法判斷TextView的字符下邊界是否超過其它字符, 如果都是中文就沒問題。 但p、q、g等字符下邊界比較低, 這類字符需要單獨判斷, 可能會漏掉一些字符。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章