Kahibaro
Discord Login Register

9.2 TextView and EditText

Introduction

In Android apps, most interactions between the user and the app involve displaying text and allowing the user to type text. TextView and EditText are the core views that handle these two tasks. TextView shows text that the user usually cannot change, while EditText lets the user enter and edit text. Understanding how to use and configure these views is essential for any form based screen, login page, search field, or simple label.

This chapter focuses on what makes TextView and EditText special, how they differ, and how to configure them effectively in XML and Kotlin.

TextView Basics

A TextView displays text on the screen, such as titles, labels, descriptions, or messages. In XML layouts, you typically define it with the android.widget.TextView class, although Android Studio will often add it simply as TextView when using the correct XML namespace.

Here is a very basic TextView in XML:

<TextView
    android:id="@+id/titleTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello, Android!" />

The android:text attribute sets the text shown. For production apps you should almost always refer to a string resource instead of hardcoding text. For example:

<TextView
    android:id="@+id/titleTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/app_name" />

In Kotlin, you access and modify a TextView after the layout is inflated. A simple example:

val titleTextView: TextView = findViewById(R.id.titleTextView)
titleTextView.text = "Welcome!"

Note that when you set text in Kotlin you typically assign a String to the text property. You can also pass a string resource id if you prefer:

titleTextView.setText(R.string.app_name)

Displaying and Formatting Text

TextView offers many attributes to control how text looks and behaves. Some of the most common are related to size, color, and style.

You control the text size in XML with android:textSize. The value usually uses sp units, which scale with the user’s font size preference:

<TextView
    ...
    android:textSize="18sp" />

You control the text color with android:textColor:

<TextView
    ...
    android:textColor="@color/black" />

You define fonts and basic styles such as bold and italic with android:textStyle and android:fontFamily. For example:

<TextView
    ...
    android:textStyle="bold"
    android:fontFamily="sans-serif-medium" />

Alignment and gravity affect how the text appears within the TextView. You use android:gravity to position the text inside the view. For example:

<TextView
    ...
    android:width="200dp"
    android:height="wrap_content"
    android:gravity="center"
    android:text="Centered text" />

This gravity is different from layout gravity, which controls how the view is positioned inside its parent. Gravity specifically affects content alignment inside the TextView.

TextView also supports line limits and wrapping. You can use android:maxLines and android:singleLine or android:ellipsize to control how long text is shown. For example:

<TextView
    ...
    android:maxLines="1"
    android:ellipsize="end"
    android:text="This is a very long text that will be cut..." />

This will cut off the text after one line and show three dots at the end, if it is longer than the view can display.

Working with Text Programmatically

When updating text in Kotlin, you can both read and write the content of a TextView. Reading the text returns a CharSequence, which you often convert to String:

val titleTextView: TextView = findViewById(R.id.titleTextView)
// Write text
titleTextView.text = "New title"
// Read text
val currentTitle: String = titleTextView.text.toString()

You can also dynamically change text color, size, or visibility:

titleTextView.setTextColor(Color.RED)
titleTextView.textSize = 24f
titleTextView.visibility = View.VISIBLE

The textSize property uses pixels in Kotlin by default, which is different from the sp unit in XML. For fine control across different screens you usually define sizes in XML resources.

Introduction to EditText

EditText extends TextView, so it inherits all the capabilities of TextView but adds user input features. It is the standard view for entering text, such as usernames, passwords, search queries, and comments.

A simple EditText in XML looks like this:

<EditText
    android:id="@+id/nameEditText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="Enter your name" />

Here, android:hint is a key attribute for EditText. The hint is shown as a light gray text when the field is empty, and disappears when the user starts typing. Unlike android:text, the hint is not actual input data, it is only a visual guide.

Just like TextView, you should usually refer to string resources for hints:

<EditText
    ...
    android:hint="@string/hint_name" />

Keyboard Types and InputType

One of the most important configurations of EditText is the keyboard type. The keyboard that appears when the user taps an EditText adapts to the data you expect. You control this with the android:inputType attribute.

For example, if the user should type an email, you set:

<EditText
    ...
    android:inputType="textEmailAddress" />

If the user should type a number:

<EditText
    ...
    android:inputType="number" />

For a phone number:

<EditText
    ...
    android:inputType="phone" />

You can combine multiple input types with a pipe character in XML, for example text plus multi line:

<EditText
    ...
    android:inputType="textMultiLine|textCapSentences" />

inputType not only affects the keyboard layout, but also how the text is handled, such as automatic capitalization or suggestions.

Always set an appropriate android:inputType for every EditText so that users get a keyboard that matches the expected input.

Handling Password Fields

For passwords and other sensitive text, EditText can automatically hide characters and display dots or a similar mask. You achieve this with a password related inputType.

A typical password field is:

<EditText
    android:id="@+id/passwordEditText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/hint_password"
    android:inputType="textPassword" />

For numeric PINs you might use:

<EditText
    ...
    android:inputType="numberPassword" />

These inputType values both mask the text and may adjust the keyboard. Some Material Components also add an icon to show or hide the password, but that belongs to Material specific components rather than basic EditText.

Reading and Writing EditText Text in Kotlin

Using EditText in Kotlin is similar to TextView, but you typically read the current input more often. You get the text when, for example, the user taps a button.

Here is a simple example:

val nameEditText: EditText = findViewById(R.id.nameEditText)
val submitButton: Button = findViewById(R.id.submitButton)
submitButton.setOnClickListener {
    val name = nameEditText.text.toString()
    // Use the 'name' value, for example show it in a TextView
}

When reading EditText content you often convert the CharSequence to String with toString(). This is especially important if you want to trim spaces or parse numbers:

val ageEditText: EditText = findViewById(R.id.ageEditText)
val ageText = ageEditText.text.toString()
val age = ageText.toIntOrNull()

Using toIntOrNull() avoids crashes if the input is not a valid number.

You can also set text programmatically, which is useful if you load data from storage or a server:

nameEditText.setText("Alice")

Hints, Placeholders, and Default Text

It is important to understand the difference between hint and text. Hint is a suggestion or placeholder that disappears when the user types. Text is the actual content of the field.

In XML:

<EditText
    ...
    android:hint="@string/hint_email"
    android:text="example@example.com" />

In this case, when the view appears, it will show example@example.com as the current value of the field, not as a hint. The hint will not be visible while text is present.

A common pattern is to use only the hint for empty fields so users know what to enter. If you also want to show an example, consider using a separate TextView for instructions, or display the example as a hint text.

In Kotlin you can access or change the hint as well as the text:

emailEditText.hint = "name@example.com"
emailEditText.setText("")

Controlling Length and Validation Basics

EditText has attributes to limit how much the user can type. The most straightforward is android:maxLength, which restricts the number of characters:

<EditText
    ...
    android:maxLength="20" />

The user will not be able to type more than 20 characters.

You can also restrict the number of lines, especially for multi line fields, using layout and input attributes. For example, a multi line field for comments:

<EditText
    android:id="@+id/commentEditText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/hint_comment"
    android:inputType="textMultiLine"
    android:minLines="3"
    android:maxLines="5" />

For validation, you often read the input and check it when a button is pressed. A simple validation could look like this:

submitButton.setOnClickListener {
    val email = emailEditText.text.toString()
    if (email.isBlank()) {
        emailEditText.error = "Email is required"
    } else {
        // Continue processing
    }
}

The error property shows a small error message near the EditText. This is not full validation logic, but it gives instant feedback to the user.

Focus and Cursor Behavior

EditText interacts with the focus system and the soft keyboard. When an EditText gains focus, the cursor appears and the keyboard opens. Some XML attributes control these behaviors.

The android:focusable and android:focusableInTouchMode attributes define if the view can receive focus. By default, EditText is focusable.

You can request focus programmatically in Kotlin:

nameEditText.requestFocus()

You can also move the cursor to a specific position in the text:

nameEditText.setSelection(nameEditText.text.length)

This places the cursor at the end of the current text. It is a common pattern when you pre fill an EditText and want the user to continue typing.

Sometimes you want the keyboard to open automatically for a specific field when the screen appears. The exact behavior depends on the activity window configuration, but calling requestFocus() and using input method utilities can encourage the keyboard to appear.

Listening to Text Changes

For more advanced user interaction, you sometimes need to react while the user is typing, for example for live search or live validation. EditText lets you observe changes by attaching a text change listener.

A typical approach uses addTextChangedListener:

val searchEditText: EditText = findViewById(R.id.searchEditText)
searchEditText.addTextChangedListener { editable ->
    val query = editable?.toString().orEmpty()
    // Use the query to filter a list or update UI
}

The lambda receives an Editable, which you convert to a string. This is a flexible way to react in real time to user input. You can also add more detailed listeners with methods that run before or after text changes, but the simple lambda is often enough.

Styling and Input Field Appearance

Because EditText extends TextView, you can style it with the same attributes for colors, fonts, and text size. In addition, EditText often has a background that looks like a field, sometimes with a border or underline, depending on the theme.

You can customize the background using android:background and colors using android:textColor, android:textColorHint, and android:textColorHighlight. For instance, to set a custom hint color:

<EditText
    ...
    android:textColorHint="@color/gray" />

The appearance of the cursor is also customizable. You can control the cursor color and width with theme attributes or custom drawables, although that usually belongs in more advanced styling chapters.

When working with Material Design libraries, you might use TextInputLayout and TextInputEditText for more advanced styling, such as floating labels and helper texts. Those are not basic EditText features, but they build on the same concepts of hints, errors, and text content.

When to Use TextView vs EditText

Choosing between TextView and EditText is simple if you focus on the purpose. Use TextView whenever you only need to display text and the user should not change it, such as labels, messages, and titles. Use EditText any time you expect the user to enter or modify text, such as login fields, forms, or search inputs.

Because EditText extends TextView, do not try to use TextView for input by enabling click listeners or similar tricks. This will not provide the correct keyboard or accessibility behavior. Instead, always use EditText for editable text.

By understanding these two views and how to configure their attributes, you can build user interfaces that clearly show information with TextView and collect user input reliably and comfortably with EditText.

Views: 1

Comments

Please login to add a comment.

Don't have an account? Register now!