Mudassir
Mudassir

Reputation: 13174

Center Alignment in Android

I want to know how to center a GUI widget programmatically. Kindly help me. I am using a LinearLayout.

Many Regards.

Upvotes: 4

Views: 19852

Answers (2)

Chromium
Chromium

Reputation: 1073

Most of the time, you don't have to do this if you defined android:gravity="center" in the layout file.

You can also perform this by getting the screen size then doing some calculations on it, but this is not recommended.

Upvotes: 9

ankitjaininfo
ankitjaininfo

Reputation: 12362

You need to set gravity for a view as CENTER_HORIZONTAL

with the markup you should use:

android:layout_gravity="center_vertical|center_horizontal"

The difference between android:gravity and android:layout_gravity is that android:gravity positions the contents of that view (i.e. what’s inside the view), whereas android:layout_gravity positions the view with respect to its parent

In the code you should use:

textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);

Upvotes: 10

Related Questions