Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 887
Mudassir Avatar asked Nov 11 '10 03:11

Mudassir


People also ask

How do you center on android?

android:gravity="center" for text center in TextView. android:gravity="center_horizontal" inner text if you want horizontally centered. android:gravity="center_vertical" inner text if you want vertically centered.

How can I center text programmatically in android?

To center align text in TextView in Kotlin Android, set android:textAlignment attribute with the value “center” in layout file, or programmatically set the textAlignment property of the TextView object with View. TEXT_ALIGNMENT_CENTER in activity file.

How do I center align text in xml?

To center align the text in this Textview through layout file, set the android:textAlignment attribute for the TextView to “center”, as shown in the following activity_main. xml layout file.


2 Answers

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);
like image 115
ankitjaininfo Avatar answered Sep 19 '22 22:09

ankitjaininfo


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.

like image 45
Chromium Avatar answered Sep 18 '22 22:09

Chromium