我有一个带有四个按钮的自定义视图。我在 Java 中创建了视图,因为我想为按钮设置动画。我想将按钮上的文本居中,但我只能水平(左右)而不是垂直地做到这一点。文字贴在顶部。
这是我可以使用的最基本的代码:
public class CopyOfGameView extends ViewGroup implements View.OnClickListener {
private Main main;
public CopyOfGameView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CopyOfGameView(Context context) {
super(context);
}
public void reset(Main main) {
this.main = main;
removeAllViews();
for (int c = 0; c < 4; c++) {
ButtonView buttonView = new ButtonView(getContext(), c);
buttonView.setText("x");
buttonView.setTextSize(6);
buttonView.setGravity(Gravity.CENTER);
addView(buttonView);
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int w = getWidth();
int h = getHeight();
int oneFourth = h / 4;
int count = getChildCount();
for (int i = 0; i < count; i++) {
ButtonView buttonView = (ButtonView) getChildAt(i);
int left = 0;
int top = oneFourth * buttonView.getRow();
int right = w;
int bottom = oneFourth * buttonView.getRow() + oneFourth;
buttonView.layout(left, top, right, bottom);
}
}
public void onClick(View v) {}
protected ButtonView findButtonView(int row) {
int count = getChildCount();
for (int i = 0; i < count; i++) {
View v = getChildAt(i);
if (v instanceof ButtonView) {
ButtonView buttonView = (ButtonView) v;
if (buttonView.getRow() == row) {
return buttonView;
}
}
}
return null;
}
protected class ButtonView extends Button {
private int row;
protected ButtonView(Context context, int row) {
super(context);
this.row = row;
Drawable image = getResources().getDrawable(R.drawable.btn_black);
setBackgroundDrawable(image);
setClickable(true);
setOnClickListener(CopyOfGameView.this);
}
public int getRow() {
return row;
}
public void setRow(int row) {
this.row = row;
}
}
}
这是正常的还是Android中的错误?如何使文本垂直居中?