Android TextView, EditText, Button, ImageView Step by step Implementation and Top 10 Questions and Answers
 .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    Last Update: April 01, 2025      18 mins read      Difficulty-Level: beginner

Android UI Components: TextView, EditText, Button, ImageView

When developing Android applications, the layout is a crucial aspect that determines how users interact with the app. The Android framework offers a variety of UI components to help layout designers create engaging and intuitive interfaces. Among these, TextView, EditText, Button, and ImageView are some of the most fundamental and commonly used components.

TextView

The TextView is a user interface component used to display text on the screen. It is versatile and can be customized to display static or dynamic strings. TextView supports various formatting options and can handle multiple lines if configured correctly.

Key Attributes:

  • android:text: Sets the text to be displayed.
  • android:textSize: Defines the size of the text.
  • android:textColor: Specifies the color of the text.
  • android:typeface: Customizes the font style (e.g., normal, sans, serif).
  • android:textStyle: Allows setting different styles such as bold, italic, or normal.
  • android:textAllCaps: Converts the text to all capital letters. This attribute is useful for making text labels more prominent.
  • android:maxLines and android:minLines: Control the maximum and minimum number of lines.
  • android:ellipsize: Trims the content of the text view if too long, replacing it with .... Common modes include: start, middle, end, and marquee.

Example Code:

<TextView
    android:id="@+id/text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    android:textSize="18sp"
    android:textColor="#FF6200EE"
    android:textStyle="bold"
    android:textAllCaps="true"
    android:maxLines="3"
    android:ellipsize="end"/>

Dynamic Text Setting:

In your Java/Kotlin code, you can dynamically set text using:

TextView textView = findViewById(R.id.text_view);
textView.setText("Dynamic Text");

or

val textView: TextView = findViewById(R.id.text_view)
textView.text = "Dynamic Text"

EditText

The EditText component is designed for taking input from users. It functions similarly to a text box in web forms, where users can type their own data. EditText supports multi-line entries and has built-in mechanisms for error checking.

Key Attributes:

  • android:hint: Displays a hint or default placeholder text when no input is provided.
  • android:digits: Restricts the characters that can be entered, useful for phone numbers or ZIP codes.
  • android:singleLine: When true, the text will not wrap to the next line (deprecated, use maxLines instead).
  • android:inputType: Specifies the type of input expected. For example: text, number, phone, date, etc.
  • android:maxLength: Limits the number of characters a user can input.

Example Code:

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

Dynamic Text Retrieval:

Retrieving text entered by the user programmatically can be done as follows:

EditText editText = findViewById(R.id.edit_text);
String inputText = editText.getText().toString();

or

val editText: EditText = findViewById(R.id.edit_text)
val inputText: String = editText.text.toString()

Button

The Button component is essential for initiating an action in response to user interaction, like submitting a form or moving to a different activity. The button text and appearance can be easily modified using XML attributes.

Key Attributes:

  • android:text: Sets the label that will appear on the button.
  • android:textSize: Specifies the font size.
  • android:textColor: Determines the text color.
  • android:background: Allows customizing the background of the button, either with a color or drawable.
  • android:drawableLeft/right/top/bottom: Adds images to various sides of the button.
  • android:onClick: Binds the button's click event to a specific method in your activity/fragment.

Example Code:

<Button
    android:id="@+id/button_submit"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Submit"
    android:textSize="14sp"
    android:textColor="#FFFFFF"
    android:background="@color/colorAccent"
    android:onClick="onSubmitClick"/>

Dynamic Click Listener:

Attaching an event listener programmatically would look something like:

Button submitButton = findViewById(R.id.button_submit);
submitButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // Handle button click here
        Toast.makeText(MainActivity.this, "Submitted!", Toast.LENGTH_SHORT).show();
    }
});

or

val submitButton: Button = findViewById(R.id.button_submit)
submitButton.setOnClickListener {
    // Handle button click here
    Toast.makeText(this, "Submitted!", Toast.LENGTH_SHORT).show()
}

ImageView

The ImageView displays images in an app. Images can be sourced from local resources or loaded from remote URLs. This component is highly customizable and provides numerous layout-related attributes.

Key Attributes:

  • android:src: Specifies the image source, either a drawable stored in resources or an image from the device's external storage.
  • android:scaleType: Controls how the image should be resized or moved to match the ImageView dimensions. Options include: fitCenter, centerCrop, centerInside, etc.
  • android:tint: Applies a tint mode to the image. Useful to change icon colors without altering original resources.
  • android:adjustViewBounds: Maintains the aspect ratio of images, resizing the ImageView's bounds to fit the image.
  • android:contentDescription: Provides a description for the image, important for accessibility purposes.

Example Code:

<ImageView
    android:id="@+id/image_view"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:src="@drawable/android_logo"
    android:scaleType="centerInside"
    android:tint="#3F51B5"
    android:adjustViewBounds="true"
    android:contentDescription="Logo of Android"/>

Setting Image Programmatically:

You can change the image at runtime using:

ImageView imageView = findViewById(R.id.image_view);
imageView.setImageResource(R.drawable.new_android_logo);

or

val imageView: ImageView = findViewById(R.id.image_view)
imageView.setImageResource(R.drawable.new_android_logo)

Conclusion

These four components – TextView, EditText, Button, and ImageView – form the bedrock of any Android application's interface. Mastery over them allows you to build a wide range of layouts, from simple forms to complex screens with embedded images. Understanding their attributes and methods is essential for creating intuitive and visually appealing apps that effectively communicate with users. While there are many more UI components available, these are among the most essential and often-used elements in Android development. Properly utilizing these features enhances both the functionality and aesthetic appeal of your application, leading to a better user experience.




Examples, Set Route, and Run the Application: Understanding Data Flow with Android TextView, EditText, Button, and ImageView

Creating an Android application involves several components, among which TextView, EditText, Button, and ImageView are fundamental UI elements. This guide is designed for beginners and will walk you through setting up a route (activity) in your app, running it on an emulator or device, and understanding how data flows between these components.


1. Setup Your Development Environment

Before diving into Android UI elements, ensure that you have the following tools installed:

  • Android Studio: The official IDE for Android development.
  • SDK Manager: Manages the Android SDK packages.
  • Android Emulator: A virtual device used to test applications.
  • Java Development Kit (JDK): A development environment for Java programming language.
  • Kotlin: A modern programming language that runs on the Java Virtual Machine and can be compiled to JavaScript source code.

For this tutorial, we’ll focus on setting up a simple project using Kotlin.


2. Create a New Project

  1. Open Android Studio and click Start a new Android Studio project.
  2. Choose “Empty Activity” and proceed to the next step.
  3. Configure your project:
    • Name: SimpleApp
    • Package name: com.example.simpleapp
    • Save location: (Choose a suitable directory on your system)
    • Language: Kotlin
    • Minimum API level: Select as per your requirement (Recommended 21: Android 5.0 Lollipop)
  4. Click Finish.

Android Studio will create the necessary directories and files required to build an Android app.


3. Designing the Layout with XML

Navigate to res/layout/activity_main.xml. We'll design a simple user interface that includes TextView, EditText, Button, and ImageView.

<!-- res/layout/activity_main.xml -->
<?xml version="1.0" encoding="utf-8"?>
<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"
    android:padding="16dp"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher_foreground" />

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

    <Button
        android:id="@+id/buttonSubmit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Submit" />

    <TextView
        android:id="@+id/textViewResult"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Your output will appear here."
        android:textSize="18sp" />

</LinearLayout>

In this layout, we've added:

  • ImageView (imageView): Displays an image. Here, we are showing the application’s default icon.
  • EditText (editTextName): Allows user input. We’re using it to accept user's name.
  • Button (buttonSubmit): On clicking this button, the app will gather the text from EditText and display it on TextView.
  • TextView (textViewResult): Shows the result after the user interacts with the app.

4. Interacting with Views in MainActivity.kt

We need to modify the MainActivity class to handle user interactions. Open MainActivity.kt and let's make some changes:

// MainActivity.kt
package com.example.simpleapp

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

class MainActivity : AppCompatActivity() {

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

        // Initialize all the views
        val imageView: ImageView = findViewById(R.id.imageView)
        val editTextName: EditText = findViewById(R.id.editTextName)
        val buttonSubmit: Button = findViewById(R.id.buttonSubmit)
        val textViewResult: TextView = findViewById(R.id.textViewResult)

        // Handle button click event
        buttonSubmit.setOnClickListener {
            // Get text from EditText
            val userName = editTextName.text.toString()
            
            // Set the text in TextView
            textViewResult.text = "Hello, $userName!"
        }
    }
}

Here's what we've done:

  • Initialize Views: We retrieve references to the ImageView, EditText, Button, and TextView using findViewById().
  • Set Click Listener: We add an OnClickListener to the Button, which handles the actions when the user clicks it.
  • Data Flow: When the user enters their name in EditText and clicks the Button, the text entered in EditText is read, processed, and then displayed in TextView.

5. Running an Android Application

To run the application, follow these steps:

  1. Connect Your Device (optional) or start an Android Emulator from Android Studio.

    • Tools > AVD Manager: Set up a new Virtual Device if you haven’t already.
  2. Click the Run Button in the toolbar at the top of Android Studio.

  3. Choose a deployment target (either connected device or emulator).

  4. Click OK to deploy the application onto the device/emulator.

Once the app successfully deploys, you should see the user interface displayed with the components we discussed earlier: an image, a field for entering text, and a button to submit the input. Upon clicking the button, TextView should update to display a greeting message including the provided name.


6. Understanding the Data Flow

Let's break down the data flow step-by-step:

  1. User Interaction:
    • User types a name in EditText.
  2. Button Click Event:
    • When the user clicks the Button, a OnClickListener block executes.
  3. Data Retrieval:
    • Inside setOnClickListener, editTextName.text.toString() function is called to fetch the text entered.
  4. Processing Data:
    • The retrieved string is used within the TextViewResult.text to construct a greeting message.
  5. Display Output:
    • TextView automatically updates its content, displaying the new greeting to the user.

Data flow in Android (or any application, for that matter) generally starts with a user action, followed by processing that action to retrieve, manipulate, or save data, and finally displaying the result of that process to the user via UI components.


Summary

  • Layout Design: Creating UI designs in XML files with elements like TextView, EditText, Button, and ImageView.
  • View Initialization: In the activity, initialize these components using findViewById().
  • Event Handling: Use listeners like Button.OnClickListener to respond to user interactions.
  • Data Manipulation: Within the listener, retrieve and process data.
  • UI Update: Update the UI components (like TextView) based on the processed data.
  • Running App: Deploy the app to an emulator or physical device to test functionality.

This step-by-step example illustrates a common scenario in Android development: how user inputs collected from an EditText element are processed and reflected in a TextView upon pressing a Button. Understanding this basic pattern sets a strong foundation for more complex applications, involving different data handling methods, UI components, and navigation across multiple activities.

As you progress, you can further enhance the application by connecting to databases, fetching data from web services, and adding more sophisticated UI elements and functionalities. Happy coding!




Top 10 Questions and Answers on Android TextView, EditText, Button, ImageView

1. What is a TextView in Android and how is it used?

Answer: A TextView is one of the most fundamental UI components in Android applications, used for displaying text to the user. It can be used for simple labels, multi-line text blocks, and even formatted text with styles such as bold, italics, colors, and more. To use a TextView, you can declare it in your XML layout file or add it programmatically to your activity or fragment.

XML Declaration Example:

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello, World!"
    android:textColor="#000000"
    android:textSize="18sp" />

Programmatic Usage:

val textView = TextView(context)
textView.text = "Hello, World!"
textView.setTextColor(Color.BLACK)
textView.textSize = 18f  // in sp

2. How do you make a TextView selectable in Android?

Answer: To make a TextView selectable so that users can long-press to select and copy text, you can set the android:textIsSelectable property to true in your XML layout file.

XML Declaration Example:

<TextView
    android:id="@+id/selectableTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="This text is selectable"
    android:textIsSelectable="true" />

Alternatively, you can set this property programmatically:

textView.isTextSelectable = true

3. What is an EditText and how does it differ from a TextView?

Answer: An EditText is a user interface component that allows the user to enter and modify text. It can handle single or multi-line text input. The primary difference between TextView and EditText is that while TextView is used for displaying text, EditText provides an editable input field for user interaction.

XML Declaration Example:

<EditText
    android:id="@+id/editText1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="Enter your text here" />

4. How can you set a hint on an EditText to guide the user?

Answer: You can set a hint on an EditText to provide guidance or a placeholder text that disappears when the user starts typing. This can be done via the android:hint attribute in XML or by using the setHint() method in code.

XML Declaration Example:

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

Programmatic Usage:

editText.hint = "Enter your name"

5. What is a Button in Android and how do you handle button click events?

Answer: A Button is a clickable widget that performs an action when the user taps it. Handling button click events is essential for making the UI interactive. This can be done using an OnClickListener.

XML Declaration Example:

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Click Me" />

Programmatic Handling:

val button = findViewById<Button>(R.id.button1)
button.setOnClickListener {
    Toast.makeText(this, "Button Clicked!", Toast.LENGTH_SHORT).show()
}

6. How do you change the background color of a Button when it is pressed?

Answer: To change the background color of a Button when it is pressed, you can use a ColorStateList defined in XML or programmatically set a custom drawable with different states.

ColorStateList Example (colors.xml):

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
          android:color="@color/pressed_color" />
    <item android:color="@color/default_color" />
</selector>

Applying to Button:

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Click Me"
    android:background="@color/button_color_selector" />

Alternatively, create a StateListDrawable programmatically and set it as the background.

7. What is an ImageView and how do you display an image from resources?

Answer: An ImageView is used to display images in an Android application. You can set images from various sources like drawable resources, bitmap files, URI, etc.

XML Declaration Example:

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/your_image" />

Programmatic Usage:

val imageView = findViewById<ImageView>(R.id.imageView1)
imageView.setImageResource(R.drawable.your_image)

8. How do you scale an image in an ImageView to fit the view?

Answer: To scale an image in an ImageView to fit the view, you can use the android:scaleType attribute. Different scale types control how the image is resized or positioned within the view.

XML Declaration Example:

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/your_image"
    android:scaleType="centerCrop" />

Common ScaleTypes:

  • center: Centers the image in the view.
  • centerCrop: Scales the image uniformly (maintaining the image's aspect ratio) so that one of the dimensions of the image will be equal to the corresponding dimension of the view.
  • centerInside: Centers the image in the view, scaling the image uniformly (maintaining the image's aspect ratio) so that both dimensions (width and height) of the image will be less than or equal to the corresponding dimension of the view.

9. How do you add an icon or drawable to a Button or TextView?

Answer: You can add an icon or drawable to a Button or TextView by using the android:drawableLeft, android:drawableRight, android:drawableTop, and android:drawableBottom attributes.

XML Declaration Example for Button:

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button with Icon"
    android:drawableStart="@drawable/ic_icon" />

For TextView, the process is similar:

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView with Icon"
    android:drawableStart="@drawable/ic_icon" />

Alternatively, you can set the drawable programmatically using the setCompoundDrawablesWithIntrinsicBounds() method.

10. How do you handle text input events in an EditText in Android?

Answer: To handle text input events in an EditText, you can use TextWatcher. This interface provides methods like beforeTextChanged(), onTextChanged(), and afterTextChanged() to respond to changes in the text.

Programmatic Example:

editText.addTextChangedListener(object : TextWatcher {
    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        // This method is called to notify you that, within s, the count characters beginning at start are about to be replaced with new text with length after.
    }

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        // This method is called to notify you that, within s, the count characters beginning at start have just replaced old text that had length before.
    }

    override fun afterTextChanged(s: Editable?) {
        // This method is called to notify you that, somewhere within s, the text has been changed.
        val currentText = s.toString()
        Toast.makeText(this@MainActivity, "Current text: $currentText", Toast.LENGTH_SHORT).show()
    }
})

This setup lets you perform actions like validating input, updating UI elements dynamically, or fetching data based on user input.

In summary, these UI components (TextView, EditText, Button, and ImageView) form the backbone of most Android applications, providing essential means of input, output, and interaction. Understanding their properties, usage, and event handling mechanisms is crucial for building effective and intuitive user interfaces.