Maybe some of you are confused, got stuck or wondered why the vertical/horizontal alignment of Textview is not working on your desired output. Following are important points and examples that may help you understand how it works:
Check the parent (LinearLayout) width/height. Let us assume that you want to positon the TextViews vertically to the center of the LinearLayout. With the layout example below, the gravity and layout_gravity will not work since the parent layout(LinearLayout) height has the same size as of its children(TextViews) and the children have no space for movement.
Gravity is used to position the content of View(Textview) and layout_gravity is used to position the TextView based on its parent(LinearLayout)
If we are going to apply gravity like the following example:
We will have the same output, Text1 and Text2 will not be centered vertically since the gravity is applied to views that have a height defined as “wrap_content”.
To center the TextViews, we need to use the “layout_gravity” attribute. Layout_gravity is used to set the alignment of TextViews with its parent(LinearLayout). See the following codes:
Now the next question is “Can we use gravity to center the content?”. The answer is Yes and we can achieve the same output as above. To do this, let us again carefully examine the codes below. Notice the value of layout_height of the two TextViews. It is set to “ wrap_content” and this is the reason why the content of Text2 is not shown at the center.
Setting the layout_height value to “match_parent” will do the trick. And our code will look like:
Now we can see that both gravity and layout_gravity can be used to align and positon views.
Hope this will help you better understand TextViews gravity.
Happy Android programming!
ABOUT THE AUTHOR
Romel Barrera
Romel has 9 years solid experience in .Net development and more than 5 years experiences leading teams, handling Software engineers and Software QA Engineers. Currently, he works on different projects in web and mobile applications.