ANDROID: Android Activity

An Activity is the fundamental UI building block in Android — a single, focused thing the user can do. Understanding how Activities are structured, how their UI is built with Views and Layouts, and how they interact with each other via Intents is essential for every Android developer.

Every screen in an Android application that a user can see and interact with is powered by an Activity. When you open your email app and see your inbox, that is an Activity. When you tap a message and it opens, you have navigated to another Activity. When you compose a reply, you are in yet another Activity.

Understanding the Activity is understanding the foundation of Android UI development.


What is an Activity?

An Activity represents a single, focused thing that the user can do. It is a self-contained screen with a specific purpose — displaying a list, showing a detail view, handling a form, presenting a settings page.

Activities serve two primary roles:

  • Present a UI — the visual interface the user sees and touches
  • Respond to a lifecycle — a series of callback methods that the Android system calls as the Activity transitions through different states

md
+---------------------------------------+
|            Android App                |
|                                       |
|   +----------+     +----------+       |
|   | Activity |     | Activity |       |
|   |  (Home)  |     | (Detail) |       |
|   +----------+     +----------+       |
|                                       |
|   Each Activity = one focused task    |
+---------------------------------------+


Activity UI: The View Hierarchy

Every Activity displays a UI built from Views. Android's UI system is organized as a hierarchy of objects that inherit from the View class.

md
+---------------------------+
|         ViewGroup         |  (root container)
|                           |
|   +---------+  +-------+  |
|   |  View   |  | View  |  |  (leaf elements)
|   | (Button)|  | (Text)|  |
|   +---------+  +-------+  |
|                           |
|   +-----------+           |
|   | ViewGroup |           |  (nested container)
|   |  +------+ |           |
|   |  | View | |           |
|   |  +------+ |           |
|   +-----------+           |
+---------------------------+

View

The View class is the fundamental building block of the Android UI. Every UI element — a button, a text label, an image — is either a View or a class that extends it.

Key characteristics of a View:

  • Occupies a rectangular area on the screen
  • Is responsible for drawing its own appearance
  • Handles user input events (touches, clicks, key presses)
  • Can be styled, measured, and positioned

Common View subclasses:

  • TextView — displays text
  • Button — a clickable button
  • ImageView — displays an image
  • EditText — an editable text input field
  • CheckBox, RadioButton, Switch — selection controls

ViewGroup

A ViewGroup is a special kind of View that acts as a container — it holds and organizes other Views or ViewGroups. ViewGroups define how their children are positioned and sized.

Layouts are the most important category of ViewGroups. They are invisible containers whose sole job is to arrange their children on the screen.


Layout Classes

Android must support an enormous variety of devices: phones of different sizes, tablets, foldables, TVs, and watches. Screen dimensions, pixel densities, and aspect ratios vary enormously. This is why responsive layout design is not optional — it is required.

Never use absolute pixel positioning. Hardcoding x=100, y=200 will look completely wrong on devices with different screen dimensions. Instead, use adaptive layout classes that position elements relative to each other or relative to the screen.

FrameLayout

FrameLayout is the simplest layout — it is designed to hold a single child view. The child is positioned at the top-left by default, though gravity attributes can move it. FrameLayout is often used as a placeholder or as a host for Fragment containers.

LinearLayout

LinearLayout arranges its children in a single line, either horizontally or vertically.

xml
<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView android:text="First" ... />
    <TextView android:text="Second" ... />
    <TextView android:text="Third" ... />

</LinearLayout>

LinearLayout supports weighted distribution — you can assign weights to children so they share available space proportionally. For example, two views with weight=1 each will split the available space equally.

RelativeLayout

RelativeLayout positions children relative to each other or relative to the parent container. One view can be told to appear below another, to the right of a sibling, or aligned to the parent's right edge.

RelativeLayout enables more flexible designs than LinearLayout, but managing many relative constraints can become complex.

ConstraintLayout

ConstraintLayout is the modern, recommended layout class for Android. It combines and extends the capabilities of all previous layout classes into a single powerful container.

md
+---------------------------------------------+
|              ConstraintLayout               |
|                                             |
|  View A ----[constraint]---- View B         |
|               |                             |
|          [guideline]                        |
|               |                             |
|  View C ----[constraint]---- parent edge    |
|                                             |
|  Supports: relative, ratio, weight, chains |
+---------------------------------------------+

ConstraintLayout supports:

  • Relative size and position — constrain a view to another view or to a parent edge
  • Ratio-based size — maintain a 16:9 aspect ratio regardless of screen size
  • Weighted relationships — distribute views proportionally using chains
  • Guideline-based positioning — create invisible guidelines at fixed or percentage positions
  • Group size/position distribution (chains) — link multiple views and distribute them evenly

Key rules to remember:

  • Every view should have both a horizontal and a vertical constraint. Without constraints, the view will be positioned at coordinate (0, 0).
  • Constraints are set visually in the Android Studio designer by dragging the circular handles at the view's midpoints.
  • ConstraintLayout works in dp (density-independent pixels), which ensures consistent visual sizing across different screen densities.

Because ConstraintLayout can replace complex nesting hierarchies of other layout classes, it produces flatter view hierarchies that render faster and are easier to maintain.


Activity Code

Every Activity has a corresponding Kotlin or Java class that defines its behavior. This class extends Activity (or more commonly, AppCompatActivity for backward compatibility).

md
+---------------------------+     +---------------------------+
|   activity_main.xml       |     |   MainActivity.kt         |
|   (Layout File)           |<--->|   (Activity Class)        |
|                           |     |                           |
|   Defines visual          |     |   Defines behavior        |
|   structure               |     |   and logic               |
+---------------------------+     +---------------------------+
              No implicit link — code must explicitly load layout

There is no automatic connection between the layout XML file and the Activity class. The Activity must explicitly load its layout using the setContentView() method, which is called in onCreate():

kotlin
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

The R Class

R is an auto-generated class that the Android build system creates from your app's resources. It provides a programmatic way to reference XML layouts, drawables, strings, colors, and every other resource in your project.

  • R.layout.activity_main — references the activity_main.xml layout file
  • R.id.my_button — references a view with android:id="@+id/my_button" in the layout
  • R.string.app_name — references a string resource
  • R.drawable.ic_launcher — references a drawable resource

To interact with a specific view defined in the layout, you retrieve it by its ID:

kotlin
val myButton = findViewById<Button>(R.id.my_button)
myButton.setOnClickListener {
    // Handle button click
}


Activity Interaction via Intents

Activities are isolated from each other. One Activity cannot directly instantiate or call methods on another Activity — this isolation is by design, enforcing the single-responsibility principle at the component level.

Instead, Activities communicate through the Intent system, which is Android's messaging mechanism for requesting actions and passing data between components.

md
Activity A                     Android System               Activity B
    |                               |                            |
    |-- Create Intent(B) ---------> |                            |
    |-- startActivity(intent) ----> |                            |
    |                               |--- Launch Activity B ----> |
    |                               |                            |

To start another Activity:

kotlin
// In Activity A: start Activity B
val intent = Intent(this, ActivityB::class.java)
startActivity(intent)

You can also pass data between Activities using Intent extras:

kotlin
// Sending data
val intent = Intent(this, DetailActivity::class.java)
intent.putExtra("user_id", 42)
intent.putExtra("user_name", "Alice")
startActivity(intent)

// Receiving data in DetailActivity
val userId = intent.getIntExtra("user_id", -1)
val userName = intent.getStringExtra("user_name")

Intents are not limited to starting Activities within your own app. They can also start Activities in other apps (like the camera, gallery, or browser), request system services, or broadcast events to other components.


The Activity Lifecycle

The Android system manages Activity instances actively. It can create, pause, stop, and destroy Activities based on user navigation and system resource pressure. The Activity lifecycle is the set of callback methods the system calls as an Activity transitions between states.

md
+------------+
|  onCreate  |  <-- Activity created, load UI here
+------------+
      |
      v
+------------+
|  onStart   |  <-- Activity becoming visible
+------------+
      |
      v
+------------+
|  onResume  |  <-- Activity in foreground, interactive
+------------+
      |
      v (user navigates away)
+------------+
|  onPause   |  <-- Activity partially hidden
+------------+
      |
      v
+------------+
|  onStop    |  <-- Activity fully hidden
+------------+
      |
      v
+------------+
| onDestroy  |  <-- Activity being destroyed
+------------+

Key lifecycle methods:

  • onCreate() — called once when the Activity is created. Initialize your UI, load data, set up bindings.
  • onResume() — called when the Activity is in the foreground and interactive. Resume animations, sensors, or camera feeds here.
  • onPause() — called when the Activity is partially obscured. Release resources that should not run when not in foreground.
  • onStop() — called when the Activity is fully invisible. Save data that needs to persist.
  • onDestroy() — called when the Activity is being permanently destroyed. Release all resources.

Understanding the lifecycle is critical for building apps that:

  • Do not drain battery by running work when the user is not looking
  • Do not crash when the phone rotates or the user multitasks
  • Do not leak memory by holding references past the Activity's useful life

Summary

ConceptPurpose
ActivitySingle-screen UI component with a lifecycle
ViewBasic UI element (Button, TextView, ImageView)
ViewGroupContainer that holds and positions Views
LayoutInvisible ViewGroup that handles positioning
ConstraintLayoutModern, recommended layout for all UIs
R classAuto-generated resource reference class
setContentView()Links an Activity to its XML layout
IntentMessage object for starting Activities and passing data

The Activity is where your Android app's UI begins. Master the Activity lifecycle and the View hierarchy, and you have the foundation for everything else in Android development.