开发中遇到不想在Button外套一层布局,加深布局层次,原生drawableTop属性不能使其居中,需要重写Button的onDraw方法。
直接上代码:
重写Button实现图片drawableTop跟文字一起居中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class DrawableVerticalButton extends Button {
public DrawableVerticalButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
canvas = getTopCanvas(canvas);
super.onDraw(canvas);
}
private Canvas getTopCanvas(Canvas canvas) {
Drawable[] drawables = getCompoundDrawables();
if (drawables == null) {
return canvas;
}
Drawable drawable = drawables[1];// 上面的drawable
if(drawable == null){
drawable = drawables[3];// 下面的drawable
}
float textSize = getPaint().getTextSize();
int drawHeight = drawable.getIntrinsicHeight();
int drawPadding = getCompoundDrawablePadding();
float contentHeight = textSize + drawHeight + drawPadding;
int topPadding = (int) (getHeight() - contentHeight);
setPadding(0, topPadding , 0, 0);
float dy = (contentHeight - getHeight())/2;
canvas.translate(0, dy);
Log.i("DrawableTopButton", "setPadding(0,"+topPadding+",0,0");
Log.i("DrawableTopButton", "translate(0,"+dy+")");
return canvas;
}
}