46

In xml you can do the following:

<TextView
    ...
    android:layout_centerHorizontal="true"
    ...
/>

How would I, when I have the instance of TextView, do this programmatically?

Onik
  • 19,396
  • 14
  • 68
  • 91
nhaarman
  • 98,571
  • 55
  • 246
  • 278

4 Answers4

112

You should use the addRule method of the RelativeLayout.LayoutParams class.

layoutparams.addRule(RelativeLayout.CENTER_HORIZONTAL);
mTextView.setLayoutParams(layoutParams);
Ron
  • 24,175
  • 8
  • 56
  • 97
28

Assuming you have a TextView called stored in a variable tv:

RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) tv.getLayoutParams();
lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
tv.setLayoutParams(lp);

Should do the trick.

nEx.Software
  • 6,782
  • 1
  • 26
  • 34
1

After 10 minutes of fighting I found how to do it in Kotlin:

N.B. - I am using view binding

val centerHorizontal = binding.tvOccupantName.layoutParams as RelativeLayout.LayoutParams
centerVertical.addRule(RelativeLayout.CENTER_HORIZONTAL)
binding.tvOccupantName.layoutParams = centerHorizontal

Hope it helps!

Top4o
  • 547
  • 6
  • 19
0

Assume that txtPhone is the textview that we are trying to place it center in horizontal.

If you are using Java then use the following code,

RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) txtPhone.getLayoutParams();
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
txtPhone.setLayoutParams(layoutParams);

If you are using Kotlin then use the following code,

val layoutParams = txtPhone.getLayoutParams() as RelativeLayout.LayoutParams
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL)
txtPhone.setLayoutParams(layoutParams)
Codemaker2015
  • 12,190
  • 6
  • 97
  • 81