Lesson Weekend

Our restaurants app looks great so far, but let’s add an additional feature which will allow users to enter an address or zip code for their desired location. This won't do much at the moment, but we will later implement the user's input as a parameter in our API request.

Adding EditText View

Let's add a form field, known as an EditText, to our welcome page where users can enter a zip code. An EditText is specific type of text field that Allows the user to interact with text in your application; usually by typing text, but cutting, copying and pasting are also supported. Drag and drop a Plain Text EditText from the Text Fields area in the Palette so that it rests centered directly above the findRestaurantsButton.

There are a variety of inputTypes such as ‘Plain Text’ or ‘Phone’. Much like in HTML, these input types restrict the input to specified characters. Specifying an input type also automatically displays the appropriate input keyboard. For example, if we specify a form field as inputType ‘phone’, our device will bring up the on-screen numbers keyboard.

Give the EditText an id, a background color so that it is visible, padding, and a bottom margin. Let's also give it a hint value to inform users what to enter in the field:

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.epicodus.myrestaurants.MainActivity"
    android:background="#000000">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id="@+id/imageView"
        android:src="@drawable/background"
        android:scaleType="centerCrop" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="MyRestaurants"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="35dp"
        android:textColor="@color/colorTextIcons"
        android:textSize="40sp"
        android:textStyle="bold" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/locationEditText"
        android:background="@color/colorTextIcons"
        android:layout_above="@+id/findRestaurantsButton"
        android:layout_marginBottom="10dp"
        android:padding="5dp"
        android:hint="Enter Zip Code"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Find Restaurants"
        android:id="@+id/findRestaurantsButton"
        android:background="@color/colorAccent"
        android:textColor="@color/colorTextIcons"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

Our EditText looks great, but we don't actually do anything with whatever text the user places inside it. Let’s fix that!

Gathering Data from EditText

In MainActivity.java let’s initialize and set a new member variable for our EditText. Then, inside the onClick() method we'll grab the user input and log it to the logcat.

Here is the resulting code in our MainActivity:

MainActivity.java
package com.epicodus.myrestaurants;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
    public static final String TAG = MainActivity.class.getSimpleName();
    private Button mFindRestaurantsButton;
    private EditText mLocationEditText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mLocationEditText = (EditText) findViewById(R.id.locationEditText);
        mFindRestaurantsButton = (Button) findViewById(R.id.findRestaurantsButton);
        mFindRestaurantsButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                String location = mLocationEditText.getText().toString();
                Log.d(TAG, location);
                Intent intent = new Intent(MainActivity.this, RestaurantsActivity.class);
                startActivity(intent);
            }
        });
    }
}

Let’s talk about what this new code is doing. We use the getText() method to grab the inputted value of our EditText and save it into a new String variable. The getText() method returns an editable data type so we have to convert it to a String using the toString() method.

Let’s run our app, fill out the form, and then check the logcat to make sure it is logging the text we inputted.


Example GitHub Repo for MyRestaurants

Terminology


  • EditText: A specific type of text field. Allows the user to interact with text in your application; usually by typing text, but cutting, copying and pasting are also supported. Text fields can have different input types, such as number, date, password or email address. These types determine which characters are permitted inside of the field.

Methods


  • getText(): Called upon a text field, returns the current contents of a text field (including an EditText), as an editable data type.

Tips


  • It is generally better practice to add EditText fields directly into the XML layout with an <EditText> element.

  • When called on a text field, the getText() method returns an editable data type. In order to log or display this data, you will need to transform it into a string with the toString() method.

Examples


EditText Field in XML

<EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/locationEditText"
        android:background="@color/colorTextIcons"
        android:layout_above="@+id/findRestaurantsButton"
        android:layout_marginBottom="10dp"
        android:padding="5dp"
        android:hint="Enter Zip Code"
        android:layout_centerHorizontal="true" />

Above is an example of an EditText element defined directly in the XML of an Android layout.

  • android:layout_width="wrap_content" and android:layout_height="wrap_content" properties set its size.

  • android:id="@+id/locationEditText" defines an id so we may target this element in our logic.

  • android:background="@color/colorTextIcons" sets the background color of the button equal to the color defined in our colors.xml file under colorTextIcons.

  • android:padding="5dp" determines the padding within the element.

  • android:hint="Enter Zip Code" inserts the text "Enter Zip Code" as a hint within the field. This text is replaced with the user's input as soon as the user starts typing into the field.

Accessing EditText Field in Android Activity

public class MainActivity extends AppCompatActivity {
    ...
    private EditText mLocationEditText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mLocationEditText = (EditText) findViewById(R.id.locationEditText);
       ...
        mFindRestaurantsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String location = mLocationEditText.getText().toString();
                Log.d(TAG, location);
                ....
            }
        });
...

The code above, from an Android Activity, does the following:

  • private EditText mLocationEditText; declares the EditText's corresponding member variable.

  • Then, in the onCreate() override, setContentView(R.layout.activity_main); applies the corresponding layout to the activity's page (this layout includes the XML for our EditText field).

  • mLocationEditText = (EditText) findViewById(R.id.locationEditText); finds the EditText by the id we defined in the XML with the line android:id="@+id/locationEditText". Assigns it to the member variable mLocationEditText.

  • Later, when the mFindRestaurantsButton is clicked (this button is not detailed here). The line String location = mLocationEditText.getText().toString(); executes, which gathers the text the user has input to our EditText field, transforms it to a string, and assigns it to the variable name location.

  • The location is then logged in the line Log.d(TAG, location);.

Example GitHub Repo for MyRestaurants

Additional Resources


  • Text Fields entry of the Android Developers documentation.
  • Edit Text entry of the same documentation.