Friday, July 1, 2016

Apa itu property gravity android? Perbedaannya dengan layout_gravity?

The other explanations here are good, but sometimes it helps to have a picture, too. The green and blue are TextViews and the other two background colors are LinearLayouts.


Notes

Don't use gravity/layout_gravity with a RelativeLayout. Use them for Views in LinearLayoutsand FrameLayouts.
If I hadn't made the width and height of the TextViews larger than the text, then setting the gravitywould have had no effect. So if you're using wrap_content on the TextView then gravity won't do anything. In the same way, if the LinearLayout had been set to wrap_content, then the layout_gravity would have had no effect on the TextViews.
The layout_gravity=center looks the same as layout_gravity=center_horizontal here because they are in a vertical linear layout. You can't center vertically in this case, so layout_gravity=centeronly centers horizontally.
So remember, layout_gravity arranges a view in its layout. Gravity arranges the content inside the view. Its easy to forget which is which. Think of this little analogy to help you remember: In daily life, "gravity" is a more common term than "layout gravity". And in daily life, the earth's gravity is a more common experience than any other kind of gravity. So think of the earth like a TextView and you are the text. Now, just like it is hard to remember what "layout gravity" is, the gravity we don't think about much in daily life is the gravity of the sun pulling on the earth. So the sun is the earth's (TextView's) parent ViewGroup (a LinearLayout or whatever) and the earth's layout gravity is its orbit in the solar system.