Centralized text in TextView programmatically
I created a TextView programmatically with text and background. I want to center text in a TextView, but the text has been centered at the top.

here's my code in the center of the text in the 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);
}
}
here's my code in 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);
How can I center the text in the TextView?
+3
Mirage01
source
to share
4 answers
Try to hope this helps you
textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL); yourTextView.setGravity(Gravity.CENTER);
check Link
+3
Janmejoy
source
to share
You can do the following:
textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
+2
AlexGo
source
to share
I am centering my text in .XML using android:gravity="center_vertical|center_horizontal"
+1
Ekonion
source
to share
You have to add it to layoutparams, for example:
LayoutParams params = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
params.weight = 1.0f;
params.gravity=17;
17 is constant for CENTER in the docs .
+1
wtsang02
source
to share