To align text in TextView at the center vertically and horizontally we need to make use of gravity attribute. Example 1 : You can use center_vertical | center_horizontal value to set the text at the center of the TextView area.
To left align the text in this Textview through layout file, set the android:textAlignment attribute for the TextView to “viewStart”, as shown in the following activity_main. xml layout file.
android:gravity="center" for text center in TextView. android:gravity="center_horizontal" inner text if you want horizontally centered. android:gravity="center_vertical" inner text if you want vertically centered. android:layout_centerInParent="true" if you want TextView in center position of parent view.
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.
I think that you are doing this: android:layout_width = "wrap_content"
If this is the case, do this: android:layout_width = "match_parent"
In general, android:gravity="right"
is different from android:layout_gravity="right"
.
The first one affects the position of the text itself within the View, so if you want it to be right-aligned, then layout_width=
should be either "fill_parent"
or "match_parent"
.
The second one affects the View's position inside its parent, in other words - aligning the object itself (edit box or text view) inside the parent view.
The better solution is the one that is the most simple, and the one that does less modification in your code behaviour.
What if you can solve this problem only with 2 Properties on your TextView
?
Instead of needing to change your LinearLayout
Properties that maybe can alter the behaviour of LinearLayout
childs?
Using this way, you do not need to change LinearLayout
properties and behaviour, you only need to add the two following properties to your target TextView
:
android:gravity="right"
android:textAlignment="gravity"
What would be better to change only your target to solve your solution instead of having a chance to cause another problem in the future, modifying your target father? think about it :)
android:layout_gravity
is used to align the text view with respect to the parent layout.
android:gravity
is used to align the text inside the text view.
Are you sure you are trying to align the text inside the text view to the right or do you want to move the text view itself to the right with respect to the parent layout or are you trying to acheive both
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