📖 2413MJET306A • Unit II • 8 Hrs

Unit II - Activity, Intent, Layout & UI Design

Comprehensive University Exam Preparation Notes, Model Question Answers & Comparison Matrices

🔍
📑 Quick Jump Navigation

📌 Syllabus Topics Covered

8 Hrs Weightage

📖 Comprehensive Theoretical Notes

Exam-Oriented Theory

2.1 & 2.2 Activity Lifecycle Callbacks & State Transitions

An Activity is the fundamental UI component representing a single visual screen in Android. As users navigate, open other apps, receive phone calls, or rotate the screen, the Android OS transitions the Activity through 7 lifecycle callback methods:

  • onCreate(): Called when the activity is first instantiated. Initialize UI views (setContentView(R.layout.activity_main)), bind variables, and initialize databases.
  • onStart(): Called when the activity becomes visible to the user, but not yet interactive.
  • onResume(): Called when the activity enters the foreground and starts accepting user touch input. Activity is in Active / Running state.
  • onPause(): Called when another activity comes into foreground (e.g., a dialog or split screen) and partially obscures this activity. Stop animations and release light resources.
  • onStop(): Called when the activity is completely hidden from view. Save persistent draft data and release heavy resources.
  • onRestart(): Called when an activity is navigated back to from the stopped state before onStart().
  • onDestroy(): Called before the activity is permanently destroyed and reclaimed from memory (via finish() or system killing).

2.3 Intents & Passing Data via Bundles

An Intent is an asynchronous messaging object used to request an action from another app component.

  • Explicit Intent: Specifies exact component class (new Intent(this, DetailActivity.class)).
  • Implicit Intent: Declares an action to perform (e.g., Intent.ACTION_DIAL with Uri.parse("tel:9876543210")).
  • Passing Data: Uses intent.putExtra("key", value) and retrieves in target activity via getIntent().getStringExtra("key").
  • Returning Results: startActivityForResult() (legacy) or modern registerForActivityResult().

2.4 - 2.7 Layout Managers, UI Widgets, and Dialog Boxes

Android Layout Managers:

  • LinearLayout: Arranges child views linearly in a single direction (android:orientation="vertical|horizontal") using android:layout_weight for proportional sizing.
  • RelativeLayout: Positions child views relative to each other (layout_toRightOf, layout_below) or relative to parent borders (layout_alignParentTop).
  • ConstraintLayout: High-performance modern layout allowing complex flat view hierarchies with flexible horizontal and vertical constraints, eliminating nested view trees.

Core UI Widgets: Button, ImageButton, FloatingActionButton, EditText, TextView, Spinner (dropdown list), ListView, ScrollView, ProgressBar (determinate/indeterminate).

Dialog Boxes: AlertDialog (with Positive, Negative, Neutral action buttons), DatePickerDialog, TimePickerDialog, and Custom Dialogs inflated via LayoutInflater.

🔑 Key Concepts & Examination Keywords

Quick Terminology
Activity Lifecycle
The deterministic sequence of 7 callback states an Activity undergoes from creation to destruction.
ConstraintLayout
A flexible layout manager that positions widgets using relative geometric constraints, reducing view hierarchy nesting.
AlertDialog
A modal dialog box prompting the user with a title, message, and up to three action buttons.
Bundle
A key-value mapping object used to pass serialized data across activities via Intents.

🎯 High-Yield Important Examination Questions

8–10 Descriptive Points Each

Q1. Explain the complete 7-stage Activity Lifecycle in Android with a state transition diagram and the role of each callback method.

10 MarksActivity LifecycleCore
📝 Detailed Examination Answer (10-Point Model):
  1. Conceptual Definition of Activity: An Activity is a core UI building block providing a visual window for user interaction, managed by the Android OS using a LIFO Back Stack.
  2. onCreate() Callback: Initializes the activity; calls `super.onCreate()`, sets the XML layout via `setContentView()`, initializes view bindings, and sets up data structures.
  3. onStart() Callback: Makes the activity visually visible to the user; registers UI-related broadcast receivers and animations.
  4. onResume() Callback: Enters the active foreground running state; starts interactive animations, acquires camera/sensor locks, and begins responding to user touch input.
  5. onPause() Callback: Invoked when another activity partially obscures the screen (dialog box, split screen); pauses animations, releases CPU-heavy resources, and commits transient changes.
  6. onStop() Callback: Invoked when the activity is completely hidden from view; releases network connections, saves draft form data to database, and pauses heavy background tasks.
  7. onRestart() Callback: Called when a stopped activity is brought back to the foreground before `onStart()` executes (e.g., user presses back button).
  8. onDestroy() Callback: Final cleanup callback before memory is reclaimed; ensures open database connections, background threads, and file handles are closed.
  9. Activity Kill by System (Memory Pressure): Under low memory conditions, the OS kills activities in `onPause()` or `onStop()` states without invoking `onDestroy()`; state is restored via `onSaveInstanceState()`.
  10. Configuration Changes (Screen Rotation): Screen rotation destroys and completely recreates the active Activity (`onDestroy() -> onCreate()`), handled using ViewModels or saved bundles.

Q2. Compare LinearLayout, RelativeLayout, and ConstraintLayout. Explain their XML attributes, layout weighting, and performance characteristics.

10 MarksLayout Managers
📝 Detailed Examination Answer (10-Point Model):
  1. Role of Layout Managers: Layout managers (subclasses of `ViewGroup`) dictate how child `View` elements are measured, arranged, and rendered on the device display.
  2. LinearLayout Architecture: Arranges child elements sequentially in a single row or single column defined by `android:orientation='horizontal|vertical'`.
  3. Proportional Sizing via layout_weight: In LinearLayout, `android:layout_weight` allocates remaining free screen space proportionally among child widgets (e.g., dividing screen into 1:2 ratio).
  4. RelativeLayout Architecture: Positions child views by establishing spatial relationships relative to sibling view IDs (e.g., `android:layout_toRightOf='@+id/btn1'`) or parent borders.
  5. ConstraintLayout Architecture: Advanced modern layout engine using geometric constraint anchors (top, bottom, start, end) to define widget positions without nesting.
  6. Overcoming Nested View Hierarchy Pitfalls: Nesting multiple LinearLayouts causes exponential multi-pass layout measurement passes ($O(2^N)$), degrading UI frame rates and causing dropped frames.
  7. Flat View Hierarchy Advantage: ConstraintLayout flattens view hierarchies into a single layout depth, allowing complex responsive layouts with optimal $O(1)$ measurement passes.
  8. Guideline, Barrier, and Chain Helpers: ConstraintLayout provides powerful virtual helper objects: Guidelines (fixed/percentage guides), Barriers (dynamic group boundaries), and Chains (flexbox-like spacing).
  9. XML Attribute Comparison: LinearLayout: `android:orientation`, `android:gravity`; RelativeLayout: `layout_below`, `layout_centerInParent`; ConstraintLayout: `app:layout_constraintTop_toBottomOf`.
  10. Google Best Practice Recommendation: ConstraintLayout is Google's official standard for all complex UI design; LinearLayout is reserved strictly for simple single-row or single-column groups.

Q3. Describe the implementation of Dialog Boxes in Android: AlertDialog (Builder pattern), DatePickerDialog, TimePickerDialog, and Custom Dialogs.

10 MarksDialog Boxes & UI
📝 Detailed Examination Answer (10-Point Model):
  1. Definition and Purpose of Dialogs: A Dialog is a small modal window that appears in front of the active activity, prompting the user to make a decision, enter data, or view an alert without leaving the screen.
  2. AlertDialog Architecture: Displays a title, a text message, optional icon, and up to three action buttons (Positive, Negative, and Neutral).
  3. AlertDialog.Builder Pattern Workflow: Constructed using fluent Builder methods: `new AlertDialog.Builder(context).setTitle('Confirm').setMessage('Delete file?').setPositiveButton('Yes', listener).create().show();`.
  4. DatePickerDialog Implementation: Pre-built system dialog allowing users to pick day, month, and year; initialized using `DatePickerDialog(context, dateSetListener, year, month, day)`.
  5. TimePickerDialog Implementation: Pre-built system dialog allowing users to select hours and minutes in 12-hour AM/PM or 24-hour clock formats.
  6. Custom Dialog Creation: Created by inflating a custom XML layout via `LayoutInflater` and passing the root view to `builder.setView(customView)` or extending `DialogFragment`.
  7. Modal Behavior and setCancelable(): Setting `builder.setCancelable(false)` prevents users from dismissing the dialog by tapping outside the dialog window boundary.
  8. DialogFragment Best Practice: Google recommends encapsulating dialogs inside `DialogFragment` to properly survive activity lifecycle and configuration changes (screen rotations).
  9. Handling User Button Clicks: Listeners (`DialogInterface.OnClickListener`) handle button taps asynchronously, executing business logic or dismissing the dialog.
  10. UI Accessibility & Styling: Custom themes (`R.style.MyDialogTheme`) enable dark/light styling matching application visual branding.

⚖️ Comprehensive Comparison & Difference Tables

8+ Comparison Criteria

📊 LinearLayout vs RelativeLayout vs ConstraintLayout

Comparison ParameterLinearLayoutRelativeLayoutConstraintLayout
Arrangement PrincipleStrictly linear (single horizontal row or vertical column).Relative positioning to sibling view IDs or parent borders.Dual-axis geometric constraints relative to other views/parent.
Hierarchy DepthRequires deep nesting for complex multi-column/row layouts.Moderate nesting required for complex layouts.Completely flat view hierarchy with zero nesting.
Performance & RenderingSlower when nested due to exponential multi-pass measurement.Moderate rendering speed; multiple measurement passes.Fastest rendering speed; optimized linear constraint solver.
Proportional SizingSupports proportional space allocation via `layout_weight`.No direct weight mechanism; requires custom margins.Supports weights via `layout_constraintHorizontal_weight` and chains.
Visual Design ToolingEasy to edit manually in XML code.Moderate XML manual editing.Rich visual drag-and-drop design editor in Android Studio.
Virtual Helper ObjectsNone (requires nested layouts).None.Provides Guidelines, Barriers, Chains, and Groups.
Memory FootprintHigh memory overhead when deeply nested.Moderate memory overhead.Minimal memory footprint due to flat layout tree.
Modern Google RecommendationUse only for simple 1D linear stacks.Legacy; largely superseded by ConstraintLayout.Primary official standard for modern Android UI design.

📊 onPause() vs onStop() Activity Callbacks

Comparison ParameteronPause() CallbackonStop() Callback
Visibility StateActivity is still PARTIALLY visible but loses user focus.Activity is COMPLETELY HIDDEN and invisible to the user.
Typical CauseA transparent dialog appears, or entering split-screen mode.User presses Home button, opens another full-screen activity.
Duration / Execution SpeedMust execute extremely fast; next activity cannot start until this completes.Can take longer to execute cleanup tasks.
Operations to PerformPause video/audio, stop animations, release camera sensor.Save persistent drafts to SQLite, release heavy network connections.
Next Lifecycle Transitions`onResume()` (if user returns) OR `onStop()` (if hidden).`onRestart() -> onStart()` (if user returns) OR `onDestroy()`.
Vulnerability to System KillRarely killed by OS except in extreme memory starvation.Highly vulnerable to being terminated by OS under memory pressure.
UI RenderingUI views remain loaded in memory and visible behind overlay.UI is completely covered by other applications.
Resource ManagementLightweight resource release.Comprehensive heavy resource release.

⚡ Quick Pre-Exam Revision Summary

5-Minute Recap
💡 Core Takeaways & High-Yield Summary
  • Activity lifecycle: `onCreate()` $\rightarrow$ `onStart()` $\rightarrow$ `onResume()` $\rightarrow$ `onPause()` $\rightarrow$ `onStop()` $\rightarrow$ `onDestroy()`.
  • `onCreate()` initializes views; `onResume()` handles interactive foreground running; `onPause()` pauses tasks; `onStop()` saves drafts.
  • Explicit Intents navigate within the app; Implicit Intents request external apps (browser, phone, camera).
  • ConstraintLayout provides flat, high-performance UI hierarchies using constraints and eliminates nested layout lag.
  • AlertDialog utilizes the Builder pattern; DatePicker/TimePicker provide native time selection dialogs.