CURRENT ARTICLE:  How to use gravity and layout_gravity on LinearLayout that includes TextViews
NEXT ARTICLE:   Top 88 Chinese Websites and Mobile Apps

How to use gravity and layout_gravity on LinearLayout that includes TextViews

Romel Barrera // Last Updated: 02 September 2016

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.

output2

  • 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: 

output3

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:

output4

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.

RECENTLY

Hot New China Websites

Great websites recently launched for the Chinese audience

Open Source Cybersecurity

Check the open source options first to save your company money!

Our Favorite Quality Assurance Tools and Processes

QA takes work! We use the best tools and processes to make it easier.

SEO Audit Tools - Our favorites at SEIRIM and Why

Get in touch with your website's SEO health with the best auditing tools

Ten Steps to China SEO Success

Gather a new perspective, tools and methodology.

Embrace a Powerful Password Paradigm

Better security is within reach!