Alex Summers Alex Summers - 3 months ago 17
Android Question

Programmatically center TextView text

I beg some leniency here, I'm just starting with the Android SDK tutorials and I'm attempting something out of interest that's not in the tutorial itself, but I would hope would be easy.

I am trying to center a

TextView
item via code horizontally and vertically (I can do it in XML just fine). I've seen several examples of how to do this when the parent is a table or some other object, but I hope this would be easier for me to grasp. (p.s. Feel free to correct my terminology).

Here is the example code from the tutorial / my working model:

package com.example.myfirstapp;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.ViewGroup.LayoutParams;
import android.widget.TextView;


public class DisplayMessageActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
textView.setGravity(View.TEXT_ALIGNMENT_GRAVITY);

setContentView(textView);
}
}


I've managed to locate the
setGravity
method, and I've tried to dabble in the
setLayoutParams
for it, but I'm not sure what the scope is for it as I can't locate what I should be importing to get the
WRAP_CONTENT
constant to resolve. From what I understood, centering and content_wrapping+gravity are two separate things. I'd like an example of how to do both in this case and maybe how/where I would have found the answer in the API documentation?

Answer
yourTextView.setGravity(Gravity.CENTER);
Comments