[Android] 零碎知识汇总 - DrawableCenterButton

package suncity.booking.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.Button;

/**
 * 让 drawbleLeft or drawableRight 与文本一起居中
 */
public class DrawableCenterButton extends Button {

  public DrawableCenterButton(Context context, AttributeSet attrs,
      int defStyle) {
    super(context, attrs, defStyle);
  }

  public DrawableCenterButton(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

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

  @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    super.onLayout(changed, left, top, right, bottom);
    Drawable[] drawables = getCompoundDrawables();
    Drawable drawableTop = drawables[1];
    if (drawableTop != null) {
      // 获取字体高度
      Paint.FontMetrics fontMetrics = getPaint().getFontMetrics();
      double textHeight = Math.ceil(fontMetrics.descent - fontMetrics.ascent);
      int drawablePadding = getCompoundDrawablePadding();
      int drawableHeight = 0;
      drawableHeight = drawableTop.getIntrinsicHeight();
      float bodyWidth = (float) (textHeight + drawableHeight + drawablePadding);
      setPadding(0, (int) (getHeight() - bodyWidth) / 2, 0, (int) (getHeight() - bodyWidth) / 2);
    }
  }

  @Override
  protected void onDraw(Canvas canvas) {
    Drawable[] drawables = getCompoundDrawables();
    if (drawables != null) {
      Drawable drawableLeft = drawables[0];
      Drawable drawableRight = drawables[2];
      if (drawableLeft != null) {
        float textWidth = getPaint().measureText(getText().toString());
        int drawablePadding = getCompoundDrawablePadding();
        int drawableWidth = 0;
        drawableWidth = drawableLeft.getIntrinsicWidth();
        float bodyWidth = textWidth + drawableWidth + drawablePadding;
        setPadding((int) (getWidth() - bodyWidth)/2, 0, (int) (getWidth() - bodyWidth)/2, 0);
      } else if (drawableRight != null) {
        float textWidth = getPaint().measureText(getText().toString());
        int drawablePadding = getCompoundDrawablePadding();
        int drawableWidth = 0;
        drawableWidth = drawableRight.getIntrinsicWidth();
        float bodyWidth = textWidth + drawableWidth + drawablePadding;
        setPadding(0, 0, (int) (getWidth() - bodyWidth), 0);
        canvas.translate((getWidth() - bodyWidth) / 2, 0);
      }
    }
    super.onDraw(canvas);
  }
}

你可能感兴趣的:([Android] 零碎知识汇总 - DrawableCenterButton)