Thursday, December 6, 2012

Android beginner tutorial: Part 12 - EditText component

Today we'll learn about the EditText widget.

The EditText component is used to allow the user enter text. EditText is a class that extends TextView, but instead of just displaying the text, it displays it in a text field with a slight border and lets the user edit the text by tapping on the field.

The main class of the EditText class is getText(). It returns the text that is currently the value of this text field, but the type of the returned value is Editable, not String. The difference is that the Editable type is a text interface, which has variable text (based on the changes in the text field), as opposed to String, which is just a piece of text that doesn't change.

There's also a method called setHint(), which displays a tip that is supposed to give the user an idea of what the text field's purpose is. Its value can be set to, for example, "Enter text here..." or "Your message..." The user sees it as the value of the textfield before he taps on it. Then it gets changed to whatever text he enters.

There are also a few methods in the class for managing text selection, such as selectAll(), setSelection(int start, int stop), setSelection(int index). The difference between the two setSelection() methods is that the first way to use it is to specify the beginning and ending indices of the selection, while the other way to use it is to just provide 1 value which sets the cursor to a specific index position.

Let's create a simple example in our activity_main.xml layout in our Android project.

Here's the code:

<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/textHint" 
        android:textSize="24sp"/>

</LinearLayout>

The strings.xml code:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Code For Food Test</string>
    <string name="textHint">Enter your message here!</string>
    <string name="menu_settings">Settings</string>

</resources>

The results:



If you test your application now, you'll see that after tapping on the text field, a keyboard UI pops up just like it usually does when entering text using the device.

That's all for today.

Thanks for reading!

No comments:

Post a Comment