views:

71

answers:

2

I can use android:gravity="bottom|center_horizontal" in xml on a textview to get my desired results but I need to do this programmatically.

My textview is inside a tablerow if that matters in a relativelayout.

I have tried:

LayoutParams layoutParams = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL); labelTV.setLayoutParams(layoutParams);

But if I understand that correctly, that would apply it to the tablerow? not the textview?

Please help, i'm lost.

A: 

Try this it will center the text in a text view:

       TextView ta  = (TextView) findViewById(R.layout.text_view);
       LayoutParams lp = new LayoutParams();
       lp.gravity= Gravity.CENTER_HORIZONTAL; 
       ta.setLayoutParams(lp);
radiofrequency
That didn't work. "lp.gravity cannot be resolved or is not a field"
Nate
Take for sure that you'll never be able to access directly an API Class field, none of them are public. It's always needed to access using getters and setters.
Maragues
Thats strange because this code works and compiles just fine for me. How would you set the weight of a textview as their is no setWeight() method?
radiofrequency
A: 
labelTV.setGravity(Gravity.CENTER | Gravity.BOTTOM);

You should search in the API before asking here... http://developer.android.com/intl/fr/reference/android/widget/TextView.html

Also, are you talking about gravity or about layout_gravity? The latter won't work in a RelativeLayout.

Maragues
Thanks that worked. I feel a little silly now for missing that. Originally the problem was setting the margins on a text field. I guess I assumed because i couldnt find a setMargin() method that setGravity wouldnt exist either.
Nate