Difference between gravity and layout_gravity in android

Do you know what is the difference between gravity and layout_gravity in android? If your answer is no, then read on the post and the difference will be clear to you soon.

What is layout_gravity in android?

layout_gravity attribute sets the position of the layout relative to its parent.

Let me show you an example.

See the image above. I have used textView inside horizontal LinearLayout. In this image center option under layout_gravity is not set i.e; layout_gravity center is false (See right side of the image under the layout_gravity option) and the textView is at the top.

Now when I set centre under layout_gravity to true the textView position will be at centre. see the image below.

That means layout_gravity is the gravity of the layout or view itself. It sets the position of the layout.

Now let’s see the gravity attribute.

What is gravity in android?

gravity attribute sets the position of the content inside the layout.

Let’s see the same example with gravity attribute.

In the image above, the content inside the textView is at the left i.e; the text ‘Hey there!’ is positioned at the left side and the center option under gravity is not set (see right side of the image under gravity option). Now, When I set the center option under gravity to true the text ‘Hey there!’ position will be at the center. See the image below.

In short :

gravity sets the position of the content inside the layout or view while the layout_gravity sets the position of the layout or view itself.

And that ends this post.

Goodbye.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: