Programmatically set android:layout_centerHorizontal

nhaarman picture nhaarman · Aug 29, 2011 · Viewed 31.1k times · Source

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?

Answer

Ronnie picture Ronnie · Aug 29, 2011

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

layoutparams.addRule(RelativeLayout.CENTER_HORIZONTAL);
mTextView.setLayoutParams(layoutParams);