Saturday, October 15, 2016

Android Gravity Example

When making a layout in android you frequently find xml attribute android:gravity. To understand what is this gravity means, I will give you an example. First look at the layout design in the picture below that is generated by xml without adding android:gravity attribute.

with no android:gravity attribute the layout is put on top.
Now look at the xml code that generate that layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Login"
        android:layout_weight="1"/>
    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Signup"
        android:layout_weight="1"/>


</LinearLayout>
Now let's put xml attribute android:gravity="center" inside LinearLayout.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:gravity="center"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Login"
        android:layout_weight="1"/>
    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Signup"
        android:layout_weight="1"/>


</LinearLayout>


Below is the result after we add android:gravity="center" to LinearLayout



From the above picture you can see that android:gravity="center" moves all of LinearLayout's children (Login and Signup button) the center of the screen.

Thank you for visiting our website. Just comment below if you have any question to ask.

No comments:

Post a Comment