Mirage01
Mirage01

Reputation: 71

center text in TextView programmatically

I created a TextView programmatically with a text and background drawable. I want to center the text in the TextView but the text was centered on the top.

enter image description here

here's my code in centering 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?

Upvotes: 3

Views: 10329

Answers (4)

Janmejoy
Janmejoy

Reputation: 2721

Try this hope it may help you

textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);   

 yourTextView.setGravity(Gravity.CENTER);

check this Link

Upvotes: 3

wtsang02
wtsang02

Reputation: 18863

You have to add it in the layoutparams like:

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.

Upvotes: 1

AlexGo
AlexGo

Reputation: 487

You can do like this:

textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);

Upvotes: 2

Eveli
Eveli

Reputation: 498

I center my text in the .XML using android:gravity="center_vertical|center_horizontal"

Upvotes: 1

Related Questions