9

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.

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69
Tchibo
  • 101
  • 1
  • 1
  • 8

6 Answers6

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);
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
0

textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);

tsiftis
  • 51
  • 1
  • 2