方法:
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(icon!=null)
canvas.drawBitmap(icon, iconBounds, buttonBounds, null);
}
public void setIcon(int res) {
this.icon = BitmapFactory.decodeResource(getResources(), res);
this.iconBounds = new Rect(0, 0, icon.getWidth(), icon.getHeight());
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
this.setTextScaleX(1.0f);
bw = MeasureSpec.getSize(widthMeasureSpec)-6;
if(tw>bw)
setTextScaleX(bw/tw);
bh = MeasureSpec.getSize(heightMeasureSpec)-6;
if(icon!=null) {
int centerX = (bw+6)/2;
int centerY = (bh+6)/2;
int mWidth = icon.getWidth()/2;
int mHeight = icon.getHeight()/2;
this.buttonBounds = new Rect(centerX-mWidth, centerY-mHeight, centerX+mWidth, centerY+mHeight);
}
}
这适用于 Froyo 和冰淇淋三明治,但不适用于 Gingerbread。按钮背景是一个 TransitionDrawable。