KEMBAR78
Introduction To Menus in Android | PDF | Menu (Computing) | Boolean Data Type
0% found this document useful (0 votes)
12 views8 pages

Introduction To Menus in Android

The document provides an overview of menus in Android, detailing types such as Options Menu, Context Menu, and Popup Menu, along with their creation and usage. It also explains Shared Preferences as a method for storing simple key-value pairs for user preferences and app settings, including how to create, read, and manage this data. Additionally, it highlights the advantages and limitations of Shared Preferences compared to other storage methods.

Uploaded by

shiva941041
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views8 pages

Introduction To Menus in Android

The document provides an overview of menus in Android, detailing types such as Options Menu, Context Menu, and Popup Menu, along with their creation and usage. It also explains Shared Preferences as a method for storing simple key-value pairs for user preferences and app settings, including how to create, read, and manage this data. Additionally, it highlights the advantages and limitations of Shared Preferences compared to other storage methods.

Uploaded by

shiva941041
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Introduction to Menus in Android

In Android, a menu is a collection of items/actions presented to the user, usually as:

• a drop-down (three-dot) menu in the app bar


• a context-based menu on long-press
• a popup menu

Menus allow users to perform actions like:

• "Save", "Edit", "Delete"


• "Settings", "Logout"
• Context-specific actions (like replying to a message)

Types of Menus in Android


1️⃣ Options Menu

• It appears in the app bar (top-right corner) as three vertical dots (⋮).
• You use it for global actions that affect the entire screen/activity.

Where?

• Tapping the menu icon or hardware menu button (in older devices)

How to Create?

Step 1: Define menu items in XML (res/menu/menu_main.xml)

<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/action_settings"
android:title="Settings"
android:icon="@drawable/ic_settings"
android:showAsAction="ifRoom"/>
</menu>

Step 2: Inflate the menu in your Activity

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

Step 3: Handle item clicks

@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
// Perform action
return true;
}
return super.onOptionsItemSelected(item);
}

Use it for:

• Settings
• Help
• About
• Logout
• Refresh, Search, etc.

2️⃣ Context Menu

• Triggered by long-pressing a view.


• Used for actions that relate specifically to the item being pressed.
• Think: Long-press a message to Delete, Forward, Copy.

How to Create?

Step 1: Register view for context menu

registerForContextMenu(myTextView);

Step 2: Override onCreateContextMenu()

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Select Action");
menu.add(0, v.getId(), 0, "Copy");
menu.add(0, v.getId(), 1, "Delete");
}
Step 3: Handle click on menu item

@Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getTitle() == "Copy") {
// Do copy
} else if (item.getTitle() == "Delete") {
// Do delete
}
return true;
}

Difference Between Option Menu & Context Menu

Feature Option Menu Context Menu


Trigger App bar (3-dot menu) Long press on view
Scope Activity-level or app-level Specific to view/item
XML Support Yes Usually defined in code
Example Settings, Logout Copy/Delete on long-press

Bonus Menus (FYI):

3️. Popup Menu

• Floats over a view (like a tooltip).


• Triggered by clicking on a specific view (like a button).
• Good for quick contextual actions.

Summary
Menus = Interactive + Organized UX.

Type Trigger Best Use Case


Options App bar General app-wide actions
Context Long-press on view Item-specific actions (e.g., list item)
Popup Tap a button Lightweight contextual actions
What are Shared Preferences?
Shared Preferences is a simple way of storing key-value pairs of primitive data types (like int,
String, boolean, etc.) persistently. It’s used for storing small, simple data — like user
preferences, app settings, or session information.

Key Facts:

• Storage Type: Data is stored as XML files.


• Scope: This data is private to your app.
• Persistence: It survives app restarts and device reboots, but doesn't support complex data
types (e.g., lists, objects).

When to Use Shared Preferences?


1. User Preferences:
o Store app settings like whether dark mode is enabled or not.
o Example: "Save user language preference."
2. Session Data:
o Store small pieces of info like whether a user is logged in or a token for user
authentication.
o Example: "Keep the user logged in."
3. Flags and States:
o Store flags like "first time app launch" or app state like the user’s last page.
o Example: "Don’t show the intro screen if already seen."
4. App Settings:
o Store settings like volume control, notifications preferences, etc.
o Example: "Remember sound setting in the app."
How to Use Shared Preferences?
Step 1: Create/Access SharedPreferences

You can get a SharedPreferences object by calling getSharedPreferences() for multi-file


preferences or getPreferences() for single-file preferences tied to the Activity.

SharedPreferences sharedPref = getSharedPreferences("MyPreferences",


Context.MODE_PRIVATE);

Here:

• "MyPreferences" is the name of the preference file.


• Context.MODE_PRIVATE means the data is only accessible by your app.

Step 2: Write Data to Shared Preferences

You write data using the SharedPreferences.Editor class. You can add various data types
like String, int, boolean, etc.

SharedPreferences.Editor editor = sharedPref.edit();


editor.putString("username", "john_doe");
editor.putInt("age", 25);
editor.putBoolean("isLoggedIn", true);
editor.apply(); // apply() is async, commit() is sync but slower

Step 3: Read Data from Shared Preferences

To read, you use the get methods that correspond to the data type you stored. Always provide a
default value in case the key doesn’t exist.

String username = sharedPref.getString("username", "defaultUser");


int age = sharedPref.getInt("age", 0);
boolean isLoggedIn = sharedPref.getBoolean("isLoggedIn", false);

If the key doesn’t exist, it returns the default value.


Step 4: Remove Data (Optional)

If you want to remove a particular entry:

SharedPreferences.Editor editor = sharedPref.edit();


editor.remove("username");
editor.apply();

Or, to clear all stored data:

SharedPreferences.Editor editor = sharedPref.edit();


editor.clear();
editor.apply();

Advantages of Shared Preferences


1. Simple and Lightweight:
Ideal for storing small amounts of data, such as user settings or app preferences. No need
for heavy databases.
2. Persistent Across App Restarts:
Data persists even after the app is closed or the device is restarted.
3. Easy to Use:
APIs are simple and intuitive, making it quick to read and write key-value pairs.
4. Private:
SharedPreferences is app-specific, meaning only your app can access the stored data
(unless you explicitly share it).

Limitations
1. Limited to Simple Data:
It’s meant for storing simple types only (e.g., String, int, boolean). For more complex
data (e.g., lists, objects), you need a more robust solution like SQLite or Room.
2. Not Ideal for Large Data:
As the data is stored as an XML file, it’s not efficient for storing large amounts of
information.
3. No Structured Querying:
Unlike a database, you can’t perform complex queries. It's just key-value storage, so it’s
not suitable for data that needs complex relationships.
Example Use Case: Storing App Settings
1. Save User Preferences (Dark Mode)
SharedPreferences sharedPref = getSharedPreferences("AppSettings",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("darkMode", true);
editor.apply();

2. Check If Dark Mode is Enabled


boolean isDarkModeEnabled = sharedPref.getBoolean("darkMode", false); //
Default: false

SharedPreferences vs Other Storage


Methods
Storage Type Use Case When to Use
User preferences, app settings,
SharedPreferences Small amounts of key-value data
flags
Complex data (e.g., users,
SQLite Database Structured data with relationships
messages)
Internal Storage Storing files like images, documents Large files, media
File sharing, backups, media
External Storage Shared files accessible outside your app
storage
Abstraction over SQLite for data Structured data with complex
Room Database
persistence queries

Summary

Shared Preferences is your go-to for simple, fast, and lightweight storage for things like:

• User settings
• Flags
• Session data
• Simple app preferences
Perfect for data that doesn’t need complex queries and relationships, but ideal when you want
persistence without the complexity.

You might also like