我以编程方式创建了TextView,文本和背景可绘制。我希望将文本居中在TextView中,但文本位于顶部。
这是我在TextView中居中的代码:
protected class TileView extends TextView{
private int tileType;
private int col;
private int row;
protected TileView(Context context, int row, int col, int tileType) {
super(context);
this.col = col;
this.row = row;
this.tileType = tileType;
String result = Integer.toString(RandomNumber(1,9));
Drawable image = getResources().getDrawable(tile_id[tileType]);
setBackgroundDrawable(image);
setClickable(true);
setText(result);
setTextAppearance(context, R.style.boldText);
setOnClickListener(GameView.this);
}
}
这是我在onLayout()
中的代码int left = oneFifth * tileView.getCol();
int top = oneFifth * tileView.getRow();
int right = oneFifth * tileView.getCol() + oneFifth;
int bottom = oneFifth * tileView.getRow() + oneFifth;
tileView.layout(left, top, right, bottom);
tileView.setGravity(Gravity.CENTER);
如何将文本居中于TextView?
答案 0 :(得分:3)
试试希望它可以帮到你
textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
yourTextView.setGravity(Gravity.CENTER);
检查此Link
答案 1 :(得分:2)
你可以这样做:
textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
答案 2 :(得分:1)
我使用android:gravity="center_vertical|center_horizontal"
答案 3 :(得分:1)
您必须将其添加到layoutparams中,例如:
LayoutParams params = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
params.weight = 1.0f;
params.gravity=17;
对于docs中的CENTER,17是常数。