In my app, I have a button that creates a TextView with a certain message. How can I set the text alignment of the text to the right of the TextView? I see the attribute in XML, but I don't know how to do it in java.
Asked
Active
Viewed 1.5k times
9
-
Which textview? awt? swing? javafx? – Jean-Baptiste Yunès Mar 04 '18 at 11:39
-
This kind: TextView tv = new TextView(MyActivity.this); – Tchibo Mar 04 '18 at 11:41
-
1Possible duplicate of [Right align text in android TextView](https://stackoverflow.com/questions/8969122/right-align-text-in-android-textview) – Jean-Baptiste Yunès Mar 04 '18 at 11:53
-
Possible duplicate of [Android TextView text alignment](https://stackoverflow.com/questions/20217834/android-textview-text-alignment) – Bö macht Blau Mar 04 '18 at 12:03
6 Answers
7
Try using
textView.setGravity(Gravity.RIGHT)

Joshua
- 110
- 6
-
While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Rosário Pereira Fernandes Mar 04 '18 at 13:43
6
You can set textview's gravity using
textLabel.setGravity(Gravity.CENTER | Gravity.BOTTOM);

fi - Anand Dubey
- 89
- 3
6
In Kotlin you can use something like the below,
val textView = TextView(context)
textView.apply {
layoutParams = TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT)
textAlignment = View.TEXT_ALIGNMENT_VIEW_START
}

Azhar
- 71
- 1
- 3
3
Here is what worked for me (in kotlin):
textView.textAlignment = View.TEXT_ALIGNMENT_CENTER

M_droid
- 2,447
- 2
- 25
- 35
0
1.) Make sure the width is not set to wrap_content
2.) If the text view is inside another container, set gravity to the container. Remember that gravity is to align text and stuff like that while layout_gravity is used to align views within a parent.
3.) TextAlign aligns text at the beginning, end, left, or right of the container. Gravity is a bit more flexible with Center_Vertical, Center_Horizontal, or Center.

Shay Ribera
- 359
- 4
- 18