- How Web Services Work
- Using Web Services in Your Applications
- Organizing Controls in the Layout Container
- Writing Java Code to Initiate Actions
Organizing Controls in the Layout Container
The user interface of an Android project is created via an XML file. The controls or views defined in the XML file for use in the Android app are laid out or organized in a layout container. Android provides several layout containers; the simplest is LinearLayout, , which displays the controls linearly, one below the other. (The default orientation of LinearLayout is vertical.)
To define the controls for your new Android project, open the activity_main.xml file by double-clicking it in the Project window; then replace the default content with the code shown in Listing 1.
Listing 1Code for activity_main.xml file.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/city_name" android:hint="Enter City Name" android:textSize="18dp" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/country_name" android:hint="Enter Country Name" android:textSize="18dp" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/submit_btn" android:text="Submit" android:textSize="18dp" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/response" android:textSize="18dp" /> </LinearLayout>
The layout file in Listing 1 uses EditText, Button, and TextView controls as follows:
- The two EditText controls display two textboxes to accept city and country names. The EditText controls are assigned the IDs city_name and country_name, respectively. Some hint text is displayed in each EditText control to guide the user about the type of data to enter there. Enter City Name is displayed in the EditText control with the ID city_name, and Enter Country Name is displayed as hint text in the EditText control with the ID country_name. The hint text automatically vanishes when the user types any text in each EditText control.
- The Button control is assigned the ID submit_btn, and it's labeled Submit.
- The TextView control is assigned the ID response. It will be used to display the weather information returned by the web service.
When laid out in a LinearLayout container, these controls appear as shown in Figure 2 (top left).
Figure 2 Two EditText controls and a Button control are displayed on application startup (top left). Weather information for the specified city and country of Chicago, USA is displayed (top right). Weather information can also be displayed when the user enters only the city name, such as Phoenix (bottom left), or nickname, such as NY (bottom right) for New York.