我想自定义一个ViewGroup,里面有4个Button,然后让它们在ViewGroup的底部显示出来,就像下图一样的:
但是布局的左上角总是会有一个Button,不知道为啥?
public class TableView extends ViewGroup {
Button[] mButtons = new Button[4];
public TableView(Context context) {
super(context);
init(context, null, -1);
}
public TableView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context, attrs, -1);
}
public TableView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr);
}
private void init(Context context, AttributeSet attrs, int defStyleAttr) {
setWillNotDraw(false);
LayoutParams l;
for (int i = 0; i < mButtons.length; i++) {
mButtons[i] = new Button(context);
l = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
mButtons[i].setLayoutParams(l);
}
mButtons[0].setText("首页");
mButtons[1].setText("上一页");
mButtons[2].setText("下一页");
mButtons[3].setText("尾页");
addView(mButtons[0]);
addView(mButtons[1]);
addView(mButtons[2]);
addView(mButtons[3]);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
for (Button b : mButtons) {
final LayoutParams lp = b.getLayoutParams();
final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
0, lp.height);
final int childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
0,
lp.width);
b.measure(childHeightMeasureSpec, childWidthMeasureSpec);
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int totalButtonWidth = 0;
for (Button bt : mButtons) {
totalButtonWidth += bt.getMeasuredWidth();
}
int left = (r - l - totalButtonWidth) / 2;
for (Button bt : mButtons) {
bt.layout(left, b - bt.getMeasuredHeight(), left + bt.getMeasuredWidth(), b);
left += bt.getMeasuredWidth();
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for (Button b : mButtons) {
b.draw(canvas);
}
}
}