Popular Searches
Popular Course Categories
Popular Courses

Using TextView, EditText, Button, and ImageView

Using TextView, EditText, Button, and ImageView

Android UI Development with XML Layouts

Using TextView, EditText, Button, and ImageView in Android

Course: Android App Development

Topic: Working with TextView, EditText, Button, and ImageView

Course Link: Android App Development Course – JustAcademy

Demo Link: Register for a Course Demo

Website: JustAcademy


1. Introduction to Android UI Components

Android applications use graphical user interface (GUI) components to display information, collect user input, perform actions, and present images. These components are commonly called Views. They are the basic building blocks of an Android application's interface.

Four frequently used Android UI components are:

  • TextView: Displays text such as headings, labels, messages, and descriptions.
  • EditText: Allows users to enter and modify text.
  • Button: Provides a clickable control that performs an action.
  • ImageView: Displays images from drawable resources or other supported image sources.

These components can be combined to build login screens, registration forms, profile pages, product details, feedback forms, and many other application screens.

2. Learning Objectives

After studying this topic, you should be able to:

  • Understand the purpose of TextView, EditText, Button, and ImageView.
  • Create these components using XML layout files.
  • Configure IDs, dimensions, text, colors, hints, and other attributes.
  • Access UI components from Kotlin code.
  • Read user input and update text dynamically.
  • Handle button click events.
  • Display images using drawable resources.
  • Validate form data and provide user feedback.
  • Apply accessibility and responsive design best practices.

3. Understanding Android Views and XML Layouts

An Android screen is generally built using a hierarchy of Views and ViewGroups. A View represents an individual UI element, while a ViewGroup contains and arranges other views.

For example, a registration screen might use a vertical LinearLayout containing a TextView heading, an ImageView logo, several EditText fields, and a Button for submission.

LinearLayout
    |
    ├── ImageView
    |
    ├── TextView
    |
    ├── EditText
    |
    ├── EditText
    |
    └── Button

XML layout files are commonly stored in the res/layout directory. They describe the screen's structure and appearance, while Kotlin or Java code handles interaction and application logic.

Common Layout Attributes

Attribute Purpose Example
android:id Assigns an identifier to a view. @+id/titleText
android:layout_width Defines the view's width. match_parent
android:layout_height Defines the view's height. wrap_content
android:padding Adds internal space around the content. 16dp
android:layout_margin Adds external space around a view. 8dp
android:visibility Controls whether a view is visible. visible
android:contentDescription Provides an accessibility description for meaningful visual content. @string/app_logo_description

Important: Use dp for layout dimensions and spacing, and sp for text sizes so that text can respond appropriately to the user's font-size settings.

4. TextView in Android

4.1 What Is TextView?

TextView is an Android UI component used to display text to the user. It is commonly used for titles, labels, descriptions, status messages, instructions, and results.

Unlike EditText, a normal TextView is primarily intended for displaying text rather than collecting editable input.

4.2 Example of TextView in XML

<TextView
    android:id="@+id/welcomeText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Welcome to Android Development"
    android:textSize="22sp"
    android:textStyle="bold"
    android:gravity="center"
    android:padding="12dp" />

4.3 Explanation of Important TextView Attributes

Attribute Description
android:text Sets the text displayed by the component.
android:textSize Sets the text size, normally in sp.
android:textColor Defines the text color.
android:textStyle Sets styles such as bold or italic.
android:gravity Controls how text is positioned inside the view.
android:padding Adds internal spacing around the text.
android:maxLines Limits the maximum number of displayed lines.
android:ellipsize Can indicate truncated text using an ellipsis when configured appropriately.

4.4 Updating TextView Using Kotlin

You can change the displayed text at runtime by accessing the view through its ID.

val welcomeText = findViewById<TextView>(R.id.welcomeText)

welcomeText.text = "Welcome to Kotlin Android Development"

This code locates the TextView and updates its displayed message. In an Activity, view references should generally be initialized after the layout has been set with setContentView().

4.5 Using TextView for Status Messages

TextView is useful for displaying feedback after a user performs an action.

val statusText = findViewById<TextView>(R.id.statusText)

statusText.text = "Your details have been submitted."

For a maintainable application, store reusable text in Android string resources instead of hardcoding every message in the layout or Kotlin code.

5. EditText in Android

5.1 What Is EditText?

EditText is an editable text field that allows users to enter, modify, or delete information. It extends TextView and provides text-entry functionality, including interaction with the on-screen keyboard.

EditText is frequently used for:

  • Names and email addresses.
  • Passwords and PINs.
  • Phone numbers.
  • Search queries.
  • Addresses and comments.
  • Numeric values and quantities.

5.2 Creating an EditText in XML

<EditText
    android:id="@+id/nameInput"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="Enter your full name"
    android:inputType="textPersonName"
    android:singleLine="true"
    android:padding="12dp" />

The hint provides guidance when the field is empty. The inputType attribute helps Android choose an appropriate keyboard and input behavior.

5.3 Common inputType Values

inputType Typical Use
text General text entry.
textPersonName Person's name.
textEmailAddress Email address with convenient keyboard characters.
textPassword Password entry with characters visually obscured.
number Numeric input.
numberPassword Numeric PIN or password.
phone Telephone number.
textMultiLine Text that can occupy multiple lines.
textPostalAddress Postal address entry.

Choose the input type that best matches the field's purpose. An inputType setting improves the input experience but does not replace validation or security checks.

5.4 Reading Input from EditText

Use the text property and convert the returned Editable value to a String when needed.

val nameInput = findViewById<EditText>(R.id.nameInput)

val enteredName = nameInput.text.toString().trim()

The trim() function removes whitespace from the beginning and end of the entered value. This is helpful when validating fields such as names and email addresses.

5.5 Validating EditText Input

Validation checks whether the user has provided acceptable information before the application continues.

val nameInput = findViewById<EditText>(R.id.nameInput)
val name = nameInput.text.toString().trim()

if (name.isEmpty()) {
    nameInput.error = "Please enter your name"
} else {
    nameInput.error = null
}

The error message appears on the relevant field. For production applications, validation should cover all required fields and should also be enforced by the backend whenever data is submitted to a server.

5.6 Monitoring Text Changes

A TextWatcher can observe changes to an EditText. It is useful for live validation, character counters, and search suggestions.

nameInput.addTextChangedListener(object : TextWatcher {
    override fun beforeTextChanged(
        s: CharSequence?,
        start: Int,
        count: Int,
        after: Int
    ) {}

    override fun onTextChanged(
        s: CharSequence?,
        start: Int,
        before: Int,
        count: Int
    ) {
        // React to changes in the entered text.
    }

    override fun afterTextChanged(s: Editable?) {
        // Perform appropriate post-edit processing.
    }
})

Add the required imports for TextWatcher and Editable. Keep expensive operations out of frequent text-change callbacks, particularly when handling search or network requests.

6. Button in Android

6.1 What Is a Button?

A Button is a user interface component that lets a user trigger an action by tapping or clicking it. It is commonly used for submitting forms, logging in, saving information, navigating between screens, and retrying failed operations.

6.2 Creating a Button in XML

<Button
    android:id="@+id/submitButton"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Submit"
    android:enabled="true" />

6.3 Handling Button Clicks in Kotlin

Use setOnClickListener to execute code when the button is tapped.

val submitButton = findViewById<Button>(R.id.submitButton)

submitButton.setOnClickListener {
    // Execute the required action.
}

The code inside the click listener runs in response to the user's interaction. The action may validate input, update the UI, save data, or start another screen.

6.4 Example: Displaying a Welcome Message

val nameInput = findViewById<EditText>(R.id.nameInput)
val welcomeText = findViewById<TextView>(R.id.welcomeText)
val submitButton = findViewById<Button>(R.id.submitButton)

submitButton.setOnClickListener {
    val name = nameInput.text.toString().trim()

    if (name.isEmpty()) {
        nameInput.error = "Please enter your name"
    } else {
        welcomeText.text = "Welcome, $name!"
    }
}

When the user enters a name and taps Submit, the application displays a personalized greeting. If the field is empty, the application displays an error instead.

6.5 Button State and Feedback

  • Enabled: The button can normally be interacted with.
  • Disabled: The button cannot be activated until enabled again.
  • Selected or pressed appearance: Visual states can indicate interaction or selection depending on the component and theme.
  • Loading state: Applications may temporarily disable a button while processing a request to prevent duplicate submissions.

Example of disabling a button during a task:

submitButton.isEnabled = false

// Perform the operation.
// Re-enable the button when the operation finishes.
submitButton.isEnabled = true

In real asynchronous operations, re-enable the button when the operation completes or fails, rather than immediately after starting the work.

7. ImageView in Android

7.1 What Is ImageView?

ImageView is an Android UI component used to display images. Images may include logos, profile pictures, product photographs, illustrations, icons, and other visual assets.

ImageView can display drawable resources bundled with an application and can also display images supplied by code. For remote images, applications commonly use an image-loading library that handles caching, loading, and memory management.

7.2 Adding an Image Resource

Place a suitable image file in the res/drawable directory. For example, an image named app_logo.png can be referenced as @drawable/app_logo.

<ImageView
    android:id="@+id/appLogo"
    android:layout_width="120dp"
    android:layout_height="120dp"
    android:src="@drawable/app_logo"
    android:contentDescription="@string/app_logo_description"
    android:scaleType="fitCenter" />

Create the corresponding string resource for the content description, or use a suitable existing resource. If the image is purely decorative and conveys no additional information, an empty content description may be appropriate.

7.3 Important ImageView Attributes

Attribute Purpose
android:src Specifies the image drawable displayed by the ImageView.
android:scaleType Controls how the image is fitted or scaled inside the view.
android:contentDescription Provides a description for accessibility when the image conveys information.
android:adjustViewBounds Allows the ImageView to adjust its bounds to preserve the drawable's aspect ratio in supported layouts.
android:background Sets a background drawable or color behind the image.
android:layout_width Defines the width of the ImageView container.
android:layout_height Defines the height of the ImageView container.

7.4 Understanding scaleType

scaleType Behavior
fitCenter Fits the image inside the view while preserving its aspect ratio and centers it.
centerCrop Fills the view while preserving aspect ratio; some image edges may be cropped.
centerInside Fits the entire image inside the view without enlarging it beyond its intrinsic size.
fitXY Scales the image to the view's exact width and height, potentially distorting the image.
center Centers the image without scaling it.

Choose the scale type according to the design. For profile photos, centerCrop is often useful. For logos and diagrams where the entire image must remain visible, fitCenter is often a better choice.

7.5 Changing an Image Using Kotlin

val appLogo = findViewById<ImageView>(R.id.appLogo)

appLogo.setImageResource(R.drawable.another_logo)

The resource referenced in Kotlin must exist in the application's drawable resources. Android resource names normally use lowercase letters, numbers, and underscores.

8. Combining All Four Components in One Screen

A practical way to learn these components is to create a simple profile form containing an image, a heading, an input field, a button, and a result message.

8.1 Create the XML Layout

Open res/layout/activity_main.xml and add the following layout. This example uses a vertical LinearLayout to arrange the components from top to bottom.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="20dp">

    <ImageView
        android:id="@+id/appLogo"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_gravity="center_horizontal"
        android:src="@drawable/ic_launcher_foreground"
        android:contentDescription="Application logo"
        android:scaleType="fitCenter" />

    <TextView
        android:id="@+id/welcomeText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Welcome"
        android:textSize="24sp"
        android:textStyle="bold"
        android:gravity="center"
        android:padding="12dp" />

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

    <Button
        android:id="@+id/submitButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Show Greeting" />

    <TextView
        android:id="@+id/resultText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Your greeting will appear here."
        android:textSize="18sp"
        android:padding="12dp" />

</LinearLayout>

The sample uses the standard launcher foreground drawable. If your project does not contain that resource, replace it with an image that exists in your res/drawable directory.

8.2 Add Kotlin Interaction Logic

Open your Activity file and connect the XML views to Kotlin. The following example assumes that the Activity uses the layout shown above.

package com.example.basicviews

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val appLogo = findViewById<ImageView>(R.id.appLogo)
        val welcomeText = findViewById<TextView>(R.id.welcomeText)
        val nameInput = findViewById<EditText>(R.id.nameInput)
        val submitButton = findViewById<Button>(R.id.submitButton)
        val resultText = findViewById<TextView>(R.id.resultText)

        welcomeText.text = "Profile Greeting"

        submitButton.setOnClickListener {
            val name = nameInput.text.toString().trim()

            if (name.isEmpty()) {
                nameInput.error = "Name is required"
                resultText.text = "Please enter your name."
            } else {
                nameInput.error = null
                resultText.text = "Hello, $name! Welcome to Android."
            }
        }
    }
}

The variable appLogo is included to demonstrate finding the ImageView. If you do not need to change the image in Kotlin, you can remove that variable. Replace the example package declaration with the package name used in your own project.

8.3 How the Application Works

  1. The Activity loads the XML layout using setContentView().
  2. findViewById() retrieves references to the views using their IDs.
  3. TextView displays the initial heading and result message.
  4. EditText accepts the user's name.
  5. Button registers a click listener.
  6. When the button is clicked, the application reads the input.
  7. If the field is empty, an error is displayed; otherwise, a personalized greeting appears.
  8. ImageView displays the selected drawable resource.

9. Using String Resources for Text

For better maintainability and localization, store reusable text in res/values/strings.xml rather than repeating hardcoded strings in XML.

<resources>
    <string name="app_name">Basic Views Demo</string>
    <string name="welcome_message">Welcome to Android</string>
    <string name="name_hint">Enter your name</string>
    <string name="submit_button">Show Greeting</string>
    <string name="app_logo_description">Application logo</string>
</resources>

You can then reference these resources in XML:

android:text="@string/welcome_message"
android:hint="@string/name_hint"

Using string resources makes it easier to translate the interface into different languages and update text consistently.

10. Styling and Layout Best Practices

10.1 Use Suitable Dimensions

  • Use match_parent when a component should occupy the available parent dimension.
  • Use wrap_content when a component should size itself to its content and measured requirements.
  • Use dp for layout dimensions and spacing.
  • Use sp for text sizes.
  • Avoid excessive fixed heights that can cut off content on small screens.

10.2 Make Input Fields Understandable

  • Give each EditText a clear label or hint.
  • Choose a suitable inputType for each field.
  • Display validation errors close to the relevant input.
  • Do not rely only on hints to explain complex or important fields.
  • Use appropriate password input types and never log sensitive user input.

10.3 Improve Button Usability

  • Use clear action labels such as Save, Submit, Continue, or Retry.
  • Provide visual feedback when an action begins or completes.
  • Prevent accidental duplicate submissions during asynchronous work.
  • Ensure the button is accessible through touch and assistive technologies.

10.4 Display Images Responsibly

  • Choose the correct scaleType for the image's purpose.
  • Use suitable image dimensions and resolutions.
  • Provide meaningful content descriptions for informative images.
  • Use an empty content description for decorative images when appropriate.
  • Use image-loading libraries for remote images rather than manually loading large bitmaps on the main thread.

11. Common Errors and Troubleshooting

Problem Possible Cause Solution
View is not found The ID is incorrect or the view belongs to another layout. Verify the XML ID and confirm that the correct layout was loaded.
Text does not update The wrong TextView reference is being used or the click listener is not triggered. Check the view ID and inspect the click listener logic.
Input is always empty The wrong EditText is being read or the user has not entered text. Verify the ID and read text.toString() after user input.
Button does nothing No click listener is registered or the action contains no effective logic. Add a listener and implement the intended action.
Image does not appear The drawable name is incorrect or the resource is missing. Check the drawable resource name and project files.
Image looks stretched The selected scaleType distorts the source image. Try fitCenter or centerCrop.
Keyboard is unsuitable The inputType does not match the field. Choose the appropriate input type, such as email, phone, or number.
Text is cut off The view has restrictive dimensions or line limits. Review the height, maxLines, ellipsize, and parent layout constraints.

12. Accessibility Considerations

Accessibility helps users with different abilities interact with the application. Good accessibility practices should be considered while designing even simple screens.

  • Use readable text sizes and sufficient color contrast.
  • Give interactive controls clear, meaningful labels.
  • Ensure input fields can be reached and understood with a screen reader.
  • Use content descriptions for images that communicate meaningful information.
  • Avoid using color alone to communicate an error or success state.
  • Keep focus order logical when navigating the screen.
  • Test with Android accessibility tools and larger font settings.

13. Practical Exercises

Exercise 1: Welcome Screen

Create a screen containing a TextView with a welcome message and an ImageView displaying your application logo.

Exercise 2: Name Entry Form

Add an EditText for the user's name and a Button that displays the entered name in a TextView. Display an error if the field is empty.

Exercise 3: Login Form

Create email and password fields, a Login button, and a TextView for feedback. Use suitable input types and validate that required fields are not empty.

Exercise 4: Change an Image

Add two drawable resources and a button that changes the ImageView source when clicked.

Exercise 5: Profile Card

Combine an ImageView, TextViews for a person's name and role, an EditText for a short message, and a Button that displays the message.

Exercise 6: Improve Accessibility

Review the labels, contrast, font sizes, image descriptions, and focus order of one of your completed screens.

14. Interview Questions and Answers

Q1. What is TextView in Android?

Answer: TextView is a UI component used to display text, including headings, labels, messages, and descriptions.

Q2. What is the difference between TextView and EditText?

Answer: TextView is primarily used to display text, while EditText allows users to enter and modify text.

Q3. What is the purpose of a Button?

Answer: A Button lets users trigger an action, such as submitting a form or saving information.

Q4. How do you handle a button click in Kotlin?

Answer: Register a listener using setOnClickListener and place the required action inside its callback.

Q5. What is ImageView used for?

Answer: ImageView displays images such as logos, photographs, icons, and illustrations.

Q6. What is the difference between dp and sp?

Answer: dp is generally used for layout dimensions and spacing, while sp is used for text sizes and responds to font scaling.

Q7. Why is inputType important in EditText?

Answer: It configures the expected kind of input and helps Android provide an appropriate keyboard and text-entry behavior.

Q8. How can you retrieve text from EditText?

Answer: Use editText.text.toString() to obtain a String representation of the entered value.

Q9. How can you change a TextView's content at runtime?

Answer: Retrieve the TextView by its ID and assign a new value to its text property.

Q10. What is the purpose of scaleType in ImageView?

Answer: scaleType determines how an image is positioned and scaled inside the ImageView's bounds.

Q11. How do you display an image from drawable resources?

Answer: Use the XML android:src attribute or call setImageResource() in Kotlin.

Q12. Why should EditText input be validated?

Answer: Validation helps prevent missing or incorrectly formatted information from being processed. Server-side validation is also necessary when data is sent to a backend.

Q13. What does findViewById() do?

Answer: It locates a view in the current view hierarchy using its resource ID.

Q14. Why use string resources instead of hardcoded text?

Answer: String resources improve maintainability and support localization into different languages.

Q15. How can you make an image accessible?

Answer: Provide an appropriate content description when the image communicates information, and avoid redundant descriptions for decorative images.

15. Quick Revision Checklist

  • TextView displays text.
  • EditText accepts editable user input.
  • Button triggers actions through click listeners.
  • ImageView displays drawable or other supported image content.
  • Use unique and correct IDs to access views.
  • Use dp for layout dimensions and sp for text sizes.
  • Choose suitable EditText input types.
  • Validate required fields before processing input.
  • Use appropriate ImageView scale types.
  • Keep reusable text in string resources.
  • Provide accessibility descriptions for meaningful images.
  • Test layouts on different screen sizes and font settings.

16. Conclusion

TextView, EditText, Button, and ImageView are fundamental components of Android interface development. TextView presents information, EditText collects user input, Button responds to user actions, and ImageView displays visual content.

By combining these components in XML layouts and connecting them to Kotlin code, developers can create interactive screens such as login forms, registration pages, profile cards, and feedback forms. Understanding their attributes, event handling, input validation, resource management, and accessibility requirements provides a strong foundation for building practical Android applications.


17. Useful Learning Resources

Previous Next
whatsapp