📖 2413MJET306A • Unit III • 4 Hrs

Unit III - Adapters and Menus

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

🔍
📑 Quick Jump Navigation

📌 Syllabus Topics Covered

4 Hrs Weightage

📖 Comprehensive Theoretical Notes

Exam-Oriented Theory

3.1 Adapters, BaseAdapter, ArrayAdapter & AdapterView

An Adapter acts as a bridge between an AdapterView (such as ListView, GridView, Spinner, RecyclerView) and the underlying data source (such as an ArrayList, Array, or SQLite Cursor). It converts individual data items into rendered row views.

Types of Adapters:

  • ArrayAdapter: Built-in adapter that binds an Array or List<T> of objects to a single TextView per row (e.g., android.R.layout.simple_list_item_1).
  • BaseAdapter: Abstract root adapter providing complete customization for complex multi-widget rows. Requires overriding 4 core methods:
    1. int getCount(): Returns total number of data items in collection.
    2. Object getItem(int position): Returns data item at specified index.
    3. long getItemId(int position): Returns unique row ID for the item.
    4. View getView(int position, View convertView, ViewGroup parent): Inflates custom XML row layout and binds data to view widgets.
  • ViewHolder Pattern: Reuses inflated row views (convertView) and caches subview references inside a static class, eliminating repetitive findViewById() calls and providing smooth 60 FPS scrolling.

3.2 Android Menu Types: Options Menu, Context Menu, and Popup Menu

Menus provide clean UI navigation without cluttering the screen:

  • 1. Options Menu: Primary menu appearing in the top App Bar / Action Bar containing global actions (Search, Settings, Help):
    • Inflated in: onCreateOptionsMenu(Menu menu) via getMenuInflater().inflate(R.menu.main_menu, menu).
    • Item selection handled in: onOptionsItemSelected(MenuItem item) using item.getItemId().
  • 2. Context Menu: Floating menu appearing when a user performs a long-press / touch-and-hold on a registered view (e.g., Delete, Copy, Share item in a list):
    • Registered via: registerForContextMenu(view).
    • Inflated in: onCreateContextMenu(...).
    • Handled in: onContextItemSelected(MenuItem item).
  • 3. Popup Menu: Modal menu anchored directly to a specific view widget (e.g., tapping an overflow 3-dots icon on a card):
    • Instantiated via: PopupMenu popup = new PopupMenu(context, anchorView);
    • Handled via: popup.setOnMenuItemClickListener(...).

🔑 Key Concepts & Examination Keywords

Quick Terminology
Adapter
A software bridge converting raw data collections into individual visual View rows for display in an AdapterView.
ViewHolder Pattern
A performance optimization pattern that caches view references to eliminate repetitive expensive findViewById() calls during list scrolling.
Options Menu
The primary action bar menu containing global activities like Search, Filter, and Settings.
Context Menu
A contextual floating menu triggered by a long-press on a registered UI element.

🎯 High-Yield Important Examination Questions

8–10 Descriptive Points Each

Q1. Explain the architectural role of Adapters in Android. Describe the 4 mandatory methods of BaseAdapter and the ViewHolder design pattern.

10 MarksAdapters & ViewHolderCore
📝 Detailed Examination Answer (10-Point Model):
  1. Bridge Architectural Concept: An Adapter decouples data storage from UI rendering, converting data models into graphical view rows requested on demand by an AdapterView.
  2. AdapterView Recycling Mechanism: Instead of instantiating 10,000 views for a 10,000-item list, AdapterView instantiates only enough views to fill the screen (~10) and recycles them as the user scrolls.
  3. BaseAdapter Method 1: getCount(): Returns total count of data items (`return dataList.size()`); dictates to the AdapterView how many rows must be scrolled.
  4. BaseAdapter Method 2: getItem(position): Returns the underlying data object entity located at the specific index position (`return dataList.get(position)`).
  5. BaseAdapter Method 3: getItemId(position): Returns a unique 64-bit numerical identifier for the item (often `position` or database primary key ID).
  6. BaseAdapter Method 4: getView(): The core rendering method: inflates XML row layouts, binds data fields to UI widgets, and returns the configured `View` to the display system.
  7. Role of convertView Parameter: When an existing row scrolls offscreen, Android passes it back as `convertView` so the developer can reuse the layout rather than inflating a new one via XML parser.
  8. The ViewHolder Pattern Optimization: Creating a static class holding widget references (`TextView title`, `ImageView icon`) and attaching it to `convertView.setTag(holder)` avoids calling `findViewById()` on every scroll.
  9. Smooth 60 FPS Performance: Combining `convertView` recycling with `ViewHolder` reference caching guarantees zero UI stuttering and smooth 60 FPS scroll performance.
  10. ArrayAdapter vs BaseAdapter Choice: Use ArrayAdapter for simple single-TextView rows; use BaseAdapter (or modern RecyclerView.Adapter) for custom multi-widget layouts.

Q2. Explain the 3 types of Menus in Android: Options Menu, Context Menu, and Popup Menu with lifecycle callbacks and XML implementation.

10 MarksAndroid Menus
📝 Detailed Examination Answer (10-Point Model):
  1. Menu Resource XML Definition: Menus are defined in `res/menu/` XML files using `` root containing ``.
  2. Options Menu Definition & Scope: The primary menu located in the top App Bar / Action Bar providing access to global application actions (Search, Settings, Account profile).
  3. Inflating Options Menu (onCreateOptionsMenu): Overridden in Activity: `getMenuInflater().inflate(R.menu.main_menu, menu); return true;` to populate top bar items.
  4. Handling Options Clicks (onOptionsItemSelected): Uses a `switch (item.getItemId())` or `if-else` block to execute specific action methods based on clicked menu ID.
  5. Context Menu Definition & Trigger: A floating modal menu that appears when a user performs a long-press (touch and hold) on a registered view element.
  6. Context Menu Registration & Callbacks: Registered in `onCreate()` via `registerForContextMenu(listView)`; inflated in `onCreateContextMenu()`; handled via `onContextItemSelected()`.
  7. Popup Menu Definition & Anchor: A modal dropdown menu anchored directly to a specific view (e.g., a three-dots overflow icon button on a card item).
  8. PopupMenu Java Instantiation: Instantiated programmatically: `PopupMenu popup = new PopupMenu(context, buttonView); popup.inflate(R.menu.popup_menu); popup.show();`.
  9. PopupMenu Click Listener: Handled using `popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { ... });`.
  10. Exam Summary Distinction: Options Menu: Global app actions (top bar); Context Menu: Item-specific actions (long press); Popup Menu: Widget-anchored dropdown (tap).

Q3. Describe the implementation of a Custom GridView / Photo Gallery using BaseAdapter and custom XML layouts.

10 MarksGridView & Custom Adapters
📝 Detailed Examination Answer (10-Point Model):
  1. GridView Component Concept: A two-dimensional scrolling grid of views arranging child items in rows and columns governed by `android:numColumns='auto_fit'` and `android:columnWidth='100dp'`.
  2. Data Model Class Construction: Create a Java POJO class (e.g., `PhotoItem`) encapsulating image resource ID (`int imageResId`) and caption string (`String title`).
  3. Custom Grid Item Layout XML: Design `grid_item_photo.xml` with an `ImageView` and `TextView` wrapped inside a `CardView` or `LinearLayout`.
  4. Custom Adapter Class Header: Create `PhotoGalleryAdapter extends BaseAdapter` accepting `Context context` and `List photoList` in constructor.
  5. Overriding Core Methods: Implement `getCount()` returning `photoList.size()` and `getItem(position)` returning `photoList.get(position)`.
  6. Defining the ViewHolder: Define `static class ViewHolder { ImageView photoImg; TextView captionTxt; }`.
  7. Implementing getView() Inflation: If `convertView == null`, inflate `grid_item_photo.xml` via `LayoutInflater.from(context)`, create ViewHolder, and attach via `setTag(holder)`.
  8. Data Binding in getView(): Retrieve ViewHolder via `(ViewHolder) convertView.getTag()`, set image via `holder.photoImg.setImageResource()`, and set text via `holder.captionTxt.setText()`.
  9. Binding Adapter to GridView in Activity: In `MainActivity.java`, instantiate adapter: `gridView.setAdapter(new PhotoGalleryAdapter(this, list));`.
  10. Handling Grid Clicks (OnItemClickListener): Attach `gridView.setOnItemClickListener((parent, view, position, id) -> { ... })` to open full-screen photo views.

⚖️ Comprehensive Comparison & Difference Tables

8+ Comparison Criteria

📊 Options Menu vs Context Menu vs Popup Menu

Comparison ParameterOptions MenuContext MenuPopup Menu
UI LocationTop App Bar / Action Bar header.Floating dialog in center of screen.Anchored directly below/above the triggering View widget.
Trigger MechanismTapping 3-dots icon on Action Bar or permanent action icon.Long-press (touch and hold) on a registered view.Normal click / tap on a specific button or view.
Registration RequirementNo registration; automatically bound to Activity.Must be explicitly registered via `registerForContextMenu(view)`.No registration; instantiated dynamically in click listener.
Scope of ActionsGlobal application actions (Search, Settings, Help).Contextual actions specific to the selected item (Delete, Edit).Secondary actions related to a specific UI widget.
Lifecycle Inflation Callback`onCreateOptionsMenu(Menu menu)``onCreateContextMenu(ContextMenu, View, ContextMenuInfo)`Programmatic: `popup.inflate(R.menu.popup_menu)`
Click Handling Callback`onOptionsItemSelected(MenuItem item)``onContextItemSelected(MenuItem item)``popup.setOnMenuItemClickListener(...)`
Number of Menus per ActivityTypically exactly one primary Options Menu per Activity.Multiple views can register separate context menus.Unlimited; dynamically created anywhere in UI hierarchy.
Modern UsageStandard in almost all top app bars.Replaced in modern UX by Contextual Action Bar (CAB).Heavily used in modern card menus and overflow buttons.

📊 ArrayAdapter vs BaseAdapter

Comparison ParameterArrayAdapterBaseAdapter
Class HierarchyConcrete subclass extending BaseAdapter.Abstract root base class implementing ListAdapter.
Row Layout CustomizationLimited; designed for simple rows with 1 or 2 TextViews.Completely unlimited; supports arbitrary complex custom layouts.
Data Source TypeExclusively arrays (`T[]`) or `java.util.List` objects.Any custom data structure, database cursor, or remote stream.
Implementation EffortMinimal effort; requires only a single constructor call.Requires creating a custom class overriding 4 core methods.
ViewHolder PatternNot easily integrated in standard ArrayAdapter without subclassing.Standard practice; natively integrated inside overridden `getView()`.
Multi-Widget BindingDifficult to bind images, buttons, and multiple text views.Easily binds multiple interactive widgets per row.
Performance ControlManaged internally by the framework.Full developer control over view recycling and memory optimization.
Best Use CaseSimple dropdown Spinners, basic text lists.E-commerce product lists, chat screens, photo galleries.

⚡ Quick Pre-Exam Revision Summary

5-Minute Recap
💡 Core Takeaways & High-Yield Summary
  • Adapters bridge data collections to `AdapterView` (ListView, GridView, Spinner).
  • BaseAdapter requires overriding 4 methods: `getCount()`, `getItem()`, `getItemId()`, `getView()`.
  • ViewHolder pattern caches subview references to avoid expensive `findViewById()` calls during scrolling.
  • Options Menu contains global action bar items (`onCreateOptionsMenu`, `onOptionsItemSelected`).
  • Context Menu triggers on long-press (`registerForContextMenu`, `onCreateContextMenu`).
  • Popup Menu anchors to a specific view button via `PopupMenu(context, anchor)`.