Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How set the android:gravity to TextView from Java side in Android

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 correctly, that would apply it to the tablerow, not the textview?

like image 353
Nate Avatar asked Sep 23 '10 05:09

Nate


People also ask

How can I center text programmatically in android?

To center align text in TextView in Kotlin Android, set android:textAlignment attribute with the value “center” in layout file, or programmatically set the textAlignment property of the TextView object with View. TEXT_ALIGNMENT_CENTER in activity file.

How do I set gravity center in RelativeLayout?

To center something in a RelativeLayout, you use android:layout_centerInParent="true" on the child. If you try to center several childs, they'll end up under/over each other.

What is the difference between gravity and layout_gravity in android?

So in general android:layout_gravity attribute is used by child views to tell their parent how they want to be placed inside it, while android:gravity is used by the parent layout to tell the child views how they should be placed inside it.

How do you set up TextView?

Set The Text of The TextView You can set the text to be displayed in the TextView either when declaring it in your layout file, or by using its setText() method. The text is set via the android:text attribute. You can either set the text as attribute value directly, or reference a text defined in the strings.


1 Answers

labelTV.setGravity(Gravity.CENTER | Gravity.BOTTOM); 

Kotlin version (thanks to Thommy)

labelTV.gravity = Gravity.CENTER_HORIZONTAL or Gravity.BOTTOM 

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

like image 89
Maragues Avatar answered Oct 01 '22 12:10

Maragues