I want to change the layout gravity for a TextView.
Via XML, you'd do that via android:layout_gravity="value"
.
I know that in order to change the gravity itself, via XML you'd do android:gravity="value"
, and in Java you'd do textview.setGravity(Gravity.VALUE);
But sadly, there's no textview.setLayoutGravity(VALUE);
, so I'm stuck.
Thanks!
Android layout_gravity for TextView in Java
5.1k Views Asked by avi12 At
4
There are 4 best solutions below
2

In Linear Layout Use :
android:layout_gravity="value"
In Relative layout use properties :
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_centerInParent="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
as per your requirement
3

To set layout_gravity programmatically
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;
youttextview.setLayoutParams(params);
Note: layout_gravity do not work with relative layout
0

The TextView was surrounded by a HorizontalScrollView which was surrounded by a ScrollView.
I discovered that nothing worked, until I set in the XML file:
<ScrollView
android:id="@+id/scrollView"
android:layout_width="match_parent" <!-- The value was "wrap_content" before, hence couldn't work -->
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="@+id/submit"
android:visibility="visible">
<!-- Some more code -->
Later on, I simply used:
textview.setGravity(Gravity.LEFT);
textview.setTextDirection(View.TEXT_DIRECTION_LTR);
And it solved my problem.
Thanks a lot to everybody!
You will need to use the correct sub class. For example if your
TextView
is in aFrameLayout
, you would need to:Be aware that
layout_gravity
orsetLayoutGravity
sets your current elements gravity in its parent,gravity
orsetGravity
sets gravity for your current elements content within the element. Refer the illustration below for more details.Example 1:
Example 2:
Example 3:
Example 4:
Example 5: