Huwebes, Enero 24, 2013

Android: Add a button to the screen


Add a button to the screen

The last component we will add to the screen is a Button.




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Hello World"
    />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"

    />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click me "           
    />

</LinearLayout>

As usual, compile and run---you will do the edit-compile-run routine lots of times, you need to get used to this. Everytime you make a change on your code or any of the assets of the android project, you need to compile and run.

It is not a pretty sight. The reason for this result are the following;
1.   The Button, TextView and EditText views are inside a single Layout container, which will arrange each view to flow from left to right
2.   The EditText's layout_width is set to wrap_content, which means in case there is a component right after it, it will generously give the space to the next view
We will make some changes to main.xml so that:
1.   The Button view does not share the layout container with the TextView and the EditText views. We will place it outside the innder LinearLayout container
2.   Since the Button view will not share the layout container with the other views, the EditText will be the last component defined in the inner LinearLayout---we should change its layout_width to "fill_parent", so it occupies whatever space is left to its right
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
    >
        <TextView 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Name "
    />
   
        <EditText
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/name"
        />
       
    </LinearLayout>
   
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click me "           
    />
   
    </LinearLayout>
The adjusted layout looks like this

Walang komento:

Mag-post ng isang Komento