Courses / Mobile Application Development (CDE-315) – BS CS 5th Semester
Week 8 Lab 8 – Create a Simple Menu and Display Messages When Menu Items Are Selected
Week 8 – Action Bar and User Interface Design · 120 min read · 9 MCQs to check yourself
Coding in Flow – Add a Toolbar (app bar) to your activity
Objective
Add an app bar (Toolbar) with an options menu to CampusMate and show a different message (Toast, Snackbar or dialog) for each menu item; then add a context menu and a popup menu. CLOs: CLO-2 (develop user interfaces with menus), CLO-4 (use Material components).
What you will build in CampusMate
The dashboard (HomeActivity, Lab 5) gets a toolbar:
| Menu item | Shown as | Message when tapped |
|---|---|---|
| Search 🔍 | Icon in the bar | Toast "Search coming soon" |
| About | Overflow ⋮ | Dialog "CampusMate v1.0 …" |
| Help | Overflow ⋮ | Snackbar with an OK action |
| Logout | Overflow ⋮ | Confirmation dialog → returns to sign-in |
Workflow
| Step | What you do | File |
|---|---|---|
| 1 | Use a NoActionBar theme | res/values/themes.xml |
| 2 | Add a MaterialToolbar to the layout | activity_home.xml |
| 3 | Create the menu resource | res/menu/main_menu.xml |
| 4 | Show the toolbar and inflate the menu | HomeActivity.java |
| 5 | Handle item clicks with messages | onOptionsItemSelected() |
| 6 | Context menu and popup menu | HomeFragment.java |
| 7 | Run and test | Emulator |
Step 1 – Theme without the default action bar
Open res/values/themes.xml and make sure the parent theme ends with NoActionBar:
<style name="Base.Theme.CampusMate" parent="Theme.Material3.DayNight.NoActionBar">
(New projects already use this.) If a theme with an action bar is used together with our own toolbar, the app crashes with "This Activity already has an action bar supplied by the window decor".
Step 2 – Add the toolbar (activity_home.xml)
Add this as the first child of the root LinearLayout from Lab 5:
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:title="CampusMate"
app:titleTextColor="@android:color/white" />
Step 3 – The menu resource (res/menu/main_menu.xml)
Right-click res/menu → New → Menu Resource File → main_menu. Add a search icon first: New → Vector Asset → search → ic_search.
<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" />
<item android:id="@+id/action_about"
android:title="About"
android:orderInCategory="1"
app:showAsAction="never" />
<item android:id="@+id/action_help"
android:title="Help"
android:orderInCategory="2"
app:showAsAction="never" />
<item android:id="@+id/action_logout"
android:title="Logout"
android:orderInCategory="3"
app:showAsAction="never" />
</menu>
| Attribute | Meaning |
|---|---|
app:showAsAction="ifRoom" |
Show as an icon in the bar if there is space |
app:showAsAction="never" |
Always in the overflow ⋮ menu |
android:orderInCategory |
Order of the items |
| Use the app: namespace (not android:) for showAsAction with AppCompat/Material. |
Step 4 – Show the toolbar and inflate the menu (HomeActivity.java)
Add to onCreate() right after setContentView(...):
MaterialToolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar); // our toolbar becomes the app bar
Add this method to the class:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu); // XML → menu items
return true; // true = show the menu
}
Step 5 – Handle clicks and show messages
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
int id = item.getItemId(); // which item was tapped?
if (id == R.id.action_search) {
Toast.makeText(this, "Search coming soon", Toast.LENGTH_SHORT).show();
return true;
} else if (id == R.id.action_about) {
new AlertDialog.Builder(this)
.setTitle("About CampusMate")
.setMessage("CampusMate v1.0\nBSCS Mobile Application Development lab project.")
.setPositiveButton("OK", null)
.show();
return true;
} else if (id == R.id.action_help) {
Snackbar.make(findViewById(R.id.main), "Need help? Ask your lab instructor.", Snackbar.LENGTH_LONG)
.setAction("OK", v -> { }) // a button on the Snackbar
.show();
return true;
} else if (id == R.id.action_logout) {
new AlertDialog.Builder(this)
.setTitle("Logout")
.setMessage("Do you want to logout?")
.setPositiveButton("Yes", (dialog, which) -> finish()) // back to sign-in
.setNegativeButton("No", null)
.show();
return true;
}
return super.onOptionsItemSelected(item);
}
Imports (Alt+Enter): android.view.Menu, android.view.MenuItem, androidx.appcompat.app.AlertDialog, com.google.android.material.appbar.MaterialToolbar, com.google.android.material.snackbar.Snackbar.
Three kinds of messages:
| Message | Use it for |
|---|---|
| Toast | Short info, disappears by itself, no button |
| Snackbar | Info at the bottom with an optional action button |
| AlertDialog | Important question that needs an answer (Yes/No) |
Step 6 – Context menu and popup menu (HomeFragment.java)
Add a TextView tvNotice ("Long-press me") and a Button btnMore ("More options") to fragment_home.xml, then in HomeFragment:
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Context menu: appears on LONG-PRESS of the registered view
TextView tvNotice = view.findViewById(R.id.tvNotice);
registerForContextMenu(tvNotice);
// Popup menu: appears anchored to the tapped button
view.findViewById(R.id.btnMore).setOnClickListener(v -> {
PopupMenu popup = new PopupMenu(requireContext(), v);
popup.getMenu().add(0, 1, 0, "Timetable"); // items added in code: (group, id, order, title)
popup.getMenu().add(0, 2, 1, "Results");
popup.setOnMenuItemClickListener(item -> {
Toast.makeText(requireContext(), item.getTitle() + " selected", Toast.LENGTH_SHORT).show();
return true;
});
popup.show();
});
}
@Override
public void onCreateContextMenu(@NonNull ContextMenu menu, @NonNull View v, ContextMenu.ContextMenuInfo info) {
super.onCreateContextMenu(menu, v, info);
menu.add(0, 10, 0, "Copy notice");
menu.add(0, 11, 1, "Share notice");
}
@Override
public boolean onContextItemSelected(@NonNull MenuItem item) {
Toast.makeText(requireContext(), item.getTitle() + " clicked", Toast.LENGTH_SHORT).show();
return true;
}
Run and test
| Test | Expected result |
|---|---|
| Open the dashboard | Toolbar "CampusMate" with a search icon and ⋮ |
| Tap search | Toast "Search coming soon" |
| ⋮ → About | Dialog with app info |
| ⋮ → Help | Snackbar with OK |
| ⋮ → Logout → Yes | Returns to the sign-in screen |
| Long-press "Long-press me" | Context menu: Copy / Share |
| Tap "More options" | Popup menu: Timetable / Results |
Common errors and fixes
| Problem | Fix |
|---|---|
| No menu appears | onCreateOptionsMenu must return true and you must call setSupportActionBar(toolbar) |
| Crash "already has an action bar" | Use a NoActionBar theme (Step 1) |
| Search shows in ⋮ instead of the bar | Use app:showAsAction, not android:showAsAction |
Short and long questions
1. (Viva) Explain the attributes used in a menu item.
Model answer
android:id – identifies the item in code; android:title – text shown (and used for accessibility); android:icon – icon for app bar display; app:showAsAction – always/ifRoom/never/withText decides whether it appears in the bar or the overflow; android:orderInCategory – ordering.
2. (Viva) Why did you use a NoActionBar theme?
Model answer
Because we supplied our own MaterialToolbar with setSupportActionBar(); a theme that already has an action bar would create two bars and throw an IllegalStateException.
3. (Viva) What is the difference between a context menu and a popup menu in your app?
Model answer
The context menu appeared when the TextView registered with registerForContextMenu was long-pressed, as a floating list handled in onContextItemSelected. The popup menu appeared anchored to the "More options" button when it was tapped, handled by setOnMenuItemClickListener.
4. (Viva) Which two methods are overridden to create and handle an options menu?
Model answer
onCreateOptionsMenu(menu) – inflates the menu XML with getMenuInflater() and returns true; onOptionsItemSelected(item) – checks item.getItemId(), performs the action (Toast, dialog, new activity) and returns true when handled.
This lesson ends with a quiz of 9 MCQs. Open the lesson on PrepOasis to take it and save your progress.
Previous: Week 8 Theory – Utilizing the Action Bar; Creating the User Interface · Next: Assignment 2 (Weeks 5–8) – "Campus Hub": Fragments, Intents, Notifications and Menus
All lessons in Mobile Application Development (CDE-315) – BS CS 5th Semester