Courses / Mobile Application Development (CDE-315) – BS CS 5th Semester

Week 8 Theory – Utilizing the Action Bar; Creating the User Interface

Week 8 – Action Bar and User Interface Design · 80 min read · 28 MCQs to check yourself

Coding in Flow – How to add a Toolbar

Coding in Flow – ConstraintLayout: understanding constraints

1. The action bar (app bar)

The action bar – now usually called the app bar – is the bar at the top of an activity that gives the app a consistent identity and navigation. Introduced in Android 3.0 Honeycomb.

[←]  App Title / Subtitle            [🔍] [⋮]
 Up    Title area                Action items  Overflow menu
Part Purpose
App icon / Up button (←) Navigates up to the parent screen
Title (and subtitle) Shows where the user is
Action items Most important actions as icons (Search, Share, Add)
Action views Widgets inside the bar, e.g. an expandable SearchView
Overflow menu (⋮) Less frequent actions (Settings, Help, About, Logout)

ActionBar vs Toolbar

ActionBar Toolbar (androidx.appcompat.widget.Toolbar / MaterialToolbar)
Provided automatically by the theme (Theme.*.DarkActionBar) A normal View placed anywhere in your layout
Fixed at the top Can be placed anywhere, animated, collapsed with scrolling (CollapsingToolbarLayout)
Limited styling Fully customisable
Accessed with supportActionBar Set as the action bar with setSupportActionBar(toolbar)

The modern approach: use a NoActionBar theme and add a MaterialToolbar inside an AppBarLayout:

<com.google.android.material.appbar.AppBarLayout
    android:layout_width="match_parent" android:layout_height="wrap_content">
    <com.google.android.material.appbar.MaterialToolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:title="Campus App" />
</com.google.android.material.appbar.AppBarLayout>
MaterialToolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
    getSupportActionBar().setTitle("Courses");
    getSupportActionBar().setSubtitle("Semester 5");
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);   // show the ← Up button
}

Using the action bar programmatically

Task Code
Change title getSupportActionBar().setTitle("Home");
Show Up button getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Hide / show getSupportActionBar().hide(); / show();
Handle Up onSupportNavigateUp() → finish() or onOptionsItemSelected with android.R.id.home
Logo/icon setDisplayShowHomeEnabled(true), setLogo(R.drawable.logo)

2. Options menu and action items

The options menu is the main menu of an activity, shown as action items and the overflow (⋮) in the app bar.

Step 1 – Define the menu in XML (res/menu/main_menu.xml)

<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:id="@+id/action_search"
          android:icon="@drawable/ic_search"
          android:title="Search"
          app:showAsAction="ifRoom"
          app:actionViewClass="androidx.appcompat.widget.SearchView" />
    <item android:id="@+id/action_share"
          android:icon="@drawable/ic_share"
          android:title="Share"
          app:showAsAction="ifRoom" />
    <item android:id="@+id/action_settings"
          android:title="Settings"
          app:showAsAction="never" />
    <item android:id="@+id/action_about"
          android:title="About"
          app:showAsAction="never" />
</menu>

showAsAction values

Value Meaning
always Always show in the bar (use for 1–2 key actions only)
ifRoom Show in the bar if there is space, otherwise in overflow
never Always in the overflow menu
withText Show the title along with the icon if space
collapseActionView Action view collapses into an icon (SearchView)

Step 2 – Inflate the menu

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main_menu, menu);
    return true;                      // true = show the menu
}

Step 3 – Handle clicks

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_share) {
        shareApp();
        return true;
    } else if (id == R.id.action_settings) {
        startActivity(new Intent(this, SettingsActivity.class));
        return true;
    } else if (id == R.id.action_about) {
        Toast.makeText(this, "Version 1.0", Toast.LENGTH_SHORT).show();
        return true;
    } else if (id == android.R.id.home) {    // Up button
        finish();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

Return true when you handled the item. Modern alternative: addMenuProvider(...) (MenuProvider API) – especially in fragments.

3. Context menus, popup menus and dialogs

Menu type Appears Use
Options menu App bar / overflow Global actions for the screen
Context menu (floating) On long press of a view Actions for that item (Edit, Delete)
Contextual action mode Replaces app bar during selection Actions on multiple selected items
Popup menu Anchored drop-down next to a view Extra actions for a button or list item (⋮ on a card)

Context menu

// in onCreate:
registerForContextMenu(tvStudent);

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo info) {
    super.onCreateContextMenu(menu, v, info);
    getMenuInflater().inflate(R.menu.context_menu, menu);
}

@Override
public boolean onContextItemSelected(@NonNull MenuItem item) {
    if (item.getItemId() == R.id.ctx_edit)   { /* edit */   return true; }
    if (item.getItemId() == R.id.ctx_delete) { /* delete */ return true; }
    return super.onContextItemSelected(item);
}

Popup menu

btnMore.setOnClickListener(v -> {
    PopupMenu popup = new PopupMenu(this, v);
    popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());
    popup.setOnMenuItemClickListener(item -> {
        Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();
        return true;
    });
    popup.show();
});

Dialogs (user feedback)

new MaterialAlertDialogBuilder(this)
        .setTitle("Delete record?")
        .setMessage("This cannot be undone.")
        .setPositiveButton("Delete", (dialog, which) -> deleteRecord())
        .setNegativeButton("Cancel", null)
        .show();

Other feedback: Toast (short message), Snackbar (message with an action such as Undo, at the bottom), DatePickerDialog / TimePickerDialog.

4. Creating the user interface

Approach A – Declarative XML layouts (most common)

Separates design from logic, gives a visual preview in the Layout Editor, and lets Android pick alternative layouts by configuration (land, sw600dp).

Approach B – Programmatically in Java

Useful when the UI depends on run-time data (e.g. adding a button for each course from a server):

LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setPadding(48, 48, 48, 48);

TextView title = new TextView(this);
title.setText("Created in code");
title.setTextSize(22);

Button button = new Button(this);
button.setText("Click me");
button.setOnClickListener(v -> title.setText("Clicked!"));

layout.addView(title);
layout.addView(button, new LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
setContentView(layout);
XML Programmatic
Clean separation, preview, easy to maintain Dynamic, data-driven
Alternative resources supported More code, harder to read
Preferred for static layouts Used for dynamic parts

Approach C – Jetpack Compose (declarative Kotlin)

@Composable
fun Greeting(name: String) {
    Column(Modifier.padding(16.dp)) {
        Text("Hello " + name, style = MaterialTheme.typography.headlineSmall)
        Button(onClick = { /* ... */ }) { Text("Click me") }
    }
}

Handling UI events

Event Listener
Click setOnClickListener { } or XML android:onClick (legacy)
Long click setOnLongClickListener { true }
Text change addTextChangedListener / doAfterTextChanged { }
Check change setOnCheckedChangeListener
Touch setOnTouchListener (MotionEvent ACTION_DOWN/MOVE/UP)
Focus setOnFocusChangeListener

Lists of data – RecyclerView (preview, used in week 10/12)

A RecyclerView shows long, scrollable lists efficiently by recycling row views. It needs a layout manager (Linear/Grid), an Adapter (creates and binds rows) and a ViewHolder (holds row views).

5. Material Design and UI guidelines

Material Design (Google, 2014; current version Material 3 / Material You, with dynamic colours from the wallpaper) gives guidelines and ready components.

Principle / guideline Practice
Consistency Use the standard app bar, navigation patterns and icons
Hierarchy One primary action per screen (a filled button or FAB)
Touch targets At least 48 × 48 dp
Spacing 8 dp grid (8, 16, 24 dp margins)
Typography Use theme type scales; text in sp
Colour Use theme colours (colorPrimary, colorSurface) and support dark theme
Feedback Ripple effects, progress indicators, Snackbars
Accessibility contentDescription, sufficient contrast (4.5 : 1), support font scaling and TalkBack
Navigation App bar + bottom navigation (3–5 items) or navigation drawer; Up vs Back behaviour

Material components: MaterialToolbar, BottomNavigationView, NavigationView (drawer), FloatingActionButton, MaterialButton, TextInputLayout, MaterialCardView, Chip, Snackbar, TabLayout, Slider, MaterialDatePicker.

Themes and styles: a style is a set of attributes applied to one view (style="@style/Title"); a theme is applied to an activity/app (android:theme in the manifest) and defines colours (colorPrimary, colorOnPrimary), shapes and typography for all views. Day/night themes live in values/themes.xml and values-night/themes.xml.

Short and long questions

1. Differentiate between ActionBar and Toolbar.

Model answer

The ActionBar is supplied automatically by the activity theme at a fixed position with limited styling. A Toolbar is an ordinary View declared in the layout (used with a NoActionBar theme and setSupportActionBar) that can be placed anywhere, styled, animated and collapsed, and it supports all action bar features.

2. What is the action bar? Name its main parts.

Model answer

The action bar (app bar) is the bar at the top of an activity providing identity, navigation and actions. Parts: app icon/Up button, title and subtitle, action items (icons), action views (e.g. SearchView) and the overflow menu.

3. Explain the values of showAsAction.

Model answer

always – always in the app bar; ifRoom – in the bar if space is available, else overflow; never – always in overflow; withText – also show the title; collapseActionView – an action view that collapses into an icon.

4. Write the steps to create an options menu.

Model answer

(1) Create res/menu/main_menu.xml with item elements (id, title, icon, app:showAsAction). (2) Override onCreateOptionsMenu and call menuInflater.inflate(R.menu.main_menu, menu), returning true. (3) Override onOptionsItemSelected, check item.itemId and perform the action, returning true when handled.

5. Differentiate between options menu, context menu and popup menu.

Model answer

The options menu holds global actions of a screen in the app bar/overflow. A context menu appears on long-press of a registered view and offers actions for that item. A popup menu is a small drop-down anchored to a particular view (e.g. a ⋮ button on a card) for extra actions.

6. List five Material Design guidelines for good UI.

Model answer

(1) Touch targets at least 48 dp. (2) Consistent spacing on an 8 dp grid. (3) One clear primary action (FAB or filled button). (4) Use theme colours, typography and support dark theme. (5) Provide feedback (ripples, progress, Snackbars) and accessibility (content descriptions, contrast, font scaling).

7. Explain how to utilise the action bar in an Android app. Describe the Toolbar, options menu, action items, overflow menu and Up navigation with complete XML and Java code.

Model answer

The action bar (app bar) at the top of an activity shows the app's identity and important actions: the Up button, title/subtitle, action items, action views and the overflow menu.

Toolbar setup: use a NoActionBar theme, add a MaterialToolbar (inside an AppBarLayout) to the layout, and in onCreate call setSupportActionBar(toolbar); then use getSupportActionBar().setTitle(...), setSubtitle(...), hide()/show().

Menu XML (res/menu/main_menu.xml): items with id, title, icon and app:showAsAction – e.g. Search (ifRoom with app:actionViewClass SearchView), Share (ifRoom), Settings and About (never, overflow).

Inflating: @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main_menu, menu); return true; }.

Handling: @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_share) { share(); return true; } if (id == R.id.action_settings) { openSettings(); return true; } if (id == android.R.id.home) { finish(); return true; } return super.onOptionsItemSelected(item); }.

Up navigation: getSupportActionBar().setDisplayHomeAsUpEnabled(true); plus android:parentActivityName in the manifest, or handle android.R.id.home. Dynamic changes: onPrepareOptionsMenu with invalidateOptionsMenu(). Fragments can contribute items through the MenuProvider API.

Guidelines: put only 1–3 frequent actions as icons; move the rest to the overflow; provide titles for accessibility; keep the app bar consistent across screens.

8. Compare creating UI in XML with creating it programmatically.

Model answer

XML layouts separate design from logic, provide visual previews, are easy to maintain and support alternative resources by configuration. Programmatic UI creates views in Java at run time, suitable for dynamic data-driven interfaces, but needs more code and is harder to maintain. Most apps use XML (or Compose) and add views in code only for dynamic parts.

9. Describe the different ways of creating the user interface in Android (XML layouts, programmatic views and Jetpack Compose). Explain event handling and Material Design guidelines.

Model answer

XML layouts: the screen is described declaratively in res/layout (ConstraintLayout, LinearLayout, TextView, Button…) and inflated with setContentView. Benefits: separation of design and code, previews in the Layout Editor, easy maintenance and alternative resources for orientation, screen size, language and night mode.

Programmatic UI: views are created in Java at run time – new LinearLayout(this), TextView tv = new TextView(this); tv.setText("...");, layout.addView(view, params), setContentView(layout). Useful when the number or type of views depends on data, but verbose.

Jetpack Compose: Google's modern declarative toolkit – @Composable functions such as Column { Text("Hello"); Button(onClick = {}) { Text("Click") } } that re-render when state changes; no XML.

Event handling: listeners such as setOnClickListener, setOnLongClickListener, addTextChangedListener/doAfterTextChanged, setOnCheckedChangeListener, setOnTouchListener, and menu callbacks (onOptionsItemSelected, onContextItemSelected). Feedback via Toast, Snackbar and dialogs.

Material Design (Material 3): consistent components (MaterialToolbar, FAB, MaterialButton, TextInputLayout, CardView, BottomNavigationView, Chips), 48 dp touch targets, 8 dp spacing, theme colours and typography, dark theme, dynamic colour, motion and ripples, and accessibility (content descriptions, contrast, scalable text). Themes apply app-wide; styles apply per view.

This lesson ends with a quiz of 28 MCQs. Open the lesson on PrepOasis to take it and save your progress.

Previous: Week 7 Lab 7 – Design a Registration Form Using TextView, EditText, Button and RadioButton · Next: Week 8 Lab 8 – Create a Simple Menu and Display Messages When Menu Items Are Selected

All lessons in Mobile Application Development (CDE-315) – BS CS 5th Semester