我以编程方式创建了一个TextView,文本和背景可绘制.我想将文本居中在TextView中,但文本居于顶部. 这是我在TextView中居中文本的代码: protected class TileView extends TextView{ private int tileType; p
这是我在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中居中文本?
试试这个希望它可以帮助你textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL); yourTextView.setGravity(Gravity.CENTER);
检查这个Link
