Center a TextView on a Android Screen

Understand How Layouts Center Views

Android RectanglesSetting the correct XML attributes to move a ViewGroup or widget (View) to the middle of the App’s display is easier if you know how Android screens are laid out. Everything on the screen is built up in rectangles, starting with the screen itself. A LinearLayout (which is a ViewGroup) sitting on the screen is a rectangle, a TextView in the LinearLayout is a rectangle. Each rectangle has two sets of layout attributes associated with it, attributes that refer to its contents and attributes that refer to its parents layout requirements. The latter is easy to determine because they all start with layout_. The number of layout_ attributes that a widget, such as a TextView, can access will vary depending upon the ViewGroup it is inside:

ViewGroup LayoutParams List

To help remember that the layout_ attributes refer to the items parent ViewGroup think of it as “attributes that lay outside” of the rectangle.

The two layout_ attributes that are always required are android:layout_width and android:layout_height. These are set to tell the parent ViewGroup how big the rectangle should be to contain the child widget or ViewGroup. These are usually set to either match_parent (previously known as fill_parent) which lets the ViewGroup decide how big the rectangle should be (usually as big as possible), or wrap_content which makes the rectangles just big enough to hold what is inside of them. However, they can also be set to physical dimensions, such as setting layout_height to 40px to make the View’s height 40 pixels high.

Centring Android TextWhen a new Android project is started in Eclipse with a blank Activity some default Hello world! text is displayed in a TextView. What if we wanted to center this in the middle of the screen (note we use the American spelling instead of the UK spelling of centre to match the Android SDK API settings). Looking at the various layout attributes for the TextView it would appear that android:layout_gravity=”center” would work. This though has no effect because the default RelativeLayout arranges child Views based on each others position. Instead to center the TextView set android:gravity=”center” for the RelativeLayout. Because this attribute does not start with layout_ it refers to it contents, in this case the TextView. This time centering works, provided the TextView’s  android:layout_width and android:layout_height are set to wrap_content, making it small enough to be moved to the central location.

See also the Layouts article in the developer documentation.

Leave a Reply

Your email address will not be published. Required fields are marked *

Human Verification: In order to verify that you are a human and not a spam bot, please enter the answer into the following box below based on the instructions contained in the graphic.