Search code examples
androidandroid-layoutcenteringandroid-relativelayout

Programmatically set android:layout_centerHorizontal


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?


Solution

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

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