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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With