0% found this document useful (0 votes)
4 views

6- Chapter 5 Menu

The document provides an overview of menus and dialog boxes in Android, detailing the three main types of menus: options menu, context menu, and popup menu. It explains how to define menus in XML, implement them in Android Studio, and includes step-by-step instructions for creating and using these menus in an application. Additionally, it covers the use of context menus and popup menus, providing code examples for each type.

Uploaded by

y2sarra
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)
4 views

6- Chapter 5 Menu

The document provides an overview of menus and dialog boxes in Android, detailing the three main types of menus: options menu, context menu, and popup menu. It explains how to define menus in XML, implement them in Android Studio, and includes step-by-step instructions for creating and using these menus in an application. Additionally, it covers the use of context menus and popup menus, providing code examples for each type.

Uploaded by

y2sarra
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/ 75

Menus and Dialog Boxes

Menus and Dialog Boxes


Menus are the common user interface component in almost all
the application. This interface provides a few options from which
the user can select an option. There are 3 types of menu types
available in Android:
➢Options menu and app bar
➢Context menu and contextual action mode
➢Popup menu

2
Menus and Dialog Boxes
How to define Menu in XML?
In android, we can build the menu on our activity page but which is
not standard practice, instead we define it in the menu resource
then we inflate that menu resource into our activity. The reason
why we should define menu in menu resource:
➢The first and most important thing it separates from our activity
so visualization and debugging is easy.
➢Separating the menu gives us flexibility like for different platform
versions, screen sizes we can make some changes to our menu
resource file.
➢Easy to manage as it’s separate from our activity.

3
Menus and Dialog Boxes
Step by Step Implementation
Step 1: Open your project in “Project” mode
Open your android project in “Project” mode If the project is already opened
in the “Android” mode.

4
Menus and Dialog Boxes
Step 2: In your project Go to the app > src > main > res as
shown in the below image.

5
Menus and Dialog Boxes
Step 3: Right-click on the res folder > New > Android
Resource Directory as shown in the below image.

6
Menus and Dialog Boxes
After selecting you can see a screen like this.
And now just hit OK.

7
Menus and Dialog Boxes
Step 4: Now you can see the menu folder inside the res folder.

8
Menus and Dialog Boxes
Step 5: Now to create a menu file select the menu folder and right-click on it and
select Menu Resource File.

9
Menus and Dialog Boxes
Step 6: Give a name to your menu file, for instance here we have given the
name as my_menu.

Then hit OK. Now you can see the my_menu.xml file inside the menu folder.
Woah, you just create your menu file in android studio. So now we just write
few lines of code to see that our menu file is working or not.

10
Menus and Dialog Boxes
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/new_game"
android:icon="@drawable/ic_baseline_local_see_24"
android:title="@string/new_game"/>
<item android:id="@+id/help"
android:icon="@drawable/ic_baseline_first_page_24"
android:title="@string/help" />
</menu>

11
Menus and Dialog Boxes
Now look at the codes you see the menu tag i.e <menu>
• <menu>: It is just a container and it holds the menu items or group of
menu items.
• <item>: It creates menu item

Ok, we just completed our 80% of work now just inflate our menu to
our MainActvity.java file

12
Menus and Dialog Boxes
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_menu, menu);
return super.onCreateOptionsMenu(menu);
}}
13
Menus and Dialog Boxes
Android Option Menus are the primary menus of
android. They can be used for settings, searching,
deleting items, etc.
When and how this item should appear as an action item
in the app bar is decided by the Show Action attribute.
The values that can be given for the showAsAction
attribute:

14
Menus and Dialog Boxes
always: This ensures that the menu will always show in the action bar.
Syntax:
app:showAsAction="always"
Example:

<item
android:id="@+id/message"
android:icon="@android:drawable/ic_menu_send"
app:showAsAction="always"
android:title="message" />

15
Menus and Dialog Boxes
never: This means that the menu will never
show, and therefore will be available through
the overflow menu Syntax:
app:showAsAction="never“
<item
android:id="@+id/exit"
app:showAsAction="never"
android:title="exit" />
16
Menus and Dialog Boxes
Below is the complete code for implementing the Options Menu in Android
is given below:
XML:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">

<item
android:id="@+id/message"
android:icon="@android:drawable/ic_menu_send"
android:title="message"
app:showAsAction="always" />

<item
android:id="@+id/picture"
android:icon="@android:drawable/ic_menu_gallery"
android:title="picture"
app:showAsAction="always|withText" />

17
Menus and Dialog Boxes
<item
android:id="@+id/mode"
android:icon="@android:drawable/ic_menu_call"
android:title="mode"
app:showAsAction="always" />

<item
android:id="@+id/about"
android:icon="@android:drawable/ic_dialog_info"
android:title="calculator"
app:showAsAction="never|withText" />

<item
android:id="@+id/exit"
android:title="exit"
app:showAsAction="never" />
</menu>

18
Menus and Dialog Boxes
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import static android.widget.Toast.LENGTH_LONG;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
19
Menus and Dialog Boxes
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.message:
Toast.makeText(getApplicationContext(), "Shows share icon",
Toast.LENGTH_SHORT).show();
return true;
case R.id.picture:
Toast.makeText(getApplicationContext(), "Shows image icon",
Toast.LENGTH_SHORT).show();
startActivity(i2);
return (true);
case R.id.mode:
Toast.makeText(getApplicationContext(), "Shows call icon",
Toast.LENGTH_SHORT).show();
return (true);

20
Menus and Dialog Boxes
case R.id.about:
Toast.makeText(getApplicationContext(), "calculator menu", Toast.LENGTH_SHORT).show();
return (true);
case R.id.exit:
finish();
return (true); }
return (super.onOptionsItemSelected(item));
}}

21
Menus and Dialog Boxes
Context Menu in Android
Here we discuss the detail of the Context Menu. In Android, the context
menu is like a floating menu and arises when the user has long-pressed or
clicked on an item and is beneficial for implementing functions that define
the specific content or reference frame effect.
The Android context menu is alike to the right-click menu in Windows or
Linux.
In the Android system, the context menu provides actions that change a
specific element or context frame in the user interface and one can provide a
context menu for any view.
The context menu will not support any object shortcuts and object icons.

22
Menus and Dialog Boxes
Step By Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to
Create/Start a New Project in Android Studio. The code for that
has been given in both Java and Kotlin Programming Language
for Android.
Step 2: Working with the XML Files
Open res -> Layout -> activity_main.xml and write the following
code. In this file add only a TextView to display a simple text.

23
Menus and Dialog Boxes
XML
<?xml version="1.0" encoding="utf-8"?>
<!-- Relative Layout to display all the details -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" <TextView
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/textView"
android:id="@+id/relLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_width="match_parent" android:layout_centerHorizontal="true"
android:layout_height="match_parent" android:layout_marginTop="20dp"
android:text="Long press me!"
android:background="#fff"
android:textColor="#000"
android:padding="16dp" android:textSize="20sp"
tools:context=".MainActivity"> android:textStyle="bold" />
</RelativeLayout>

24
Menus and Dialog Boxes
Step 3: Working with the MainActivity file
Open the app -> Java -> Package -> Mainactivity.java file. In this step, add the code to
show the ContextMenu. Whenever the app will start make a long click on a text and display
the number of options to select of them for specific purposes. Comments are added inside
the code to understand the code in more detail.
import android.graphics.Color;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
TextView textView;
RelativeLayout relativeLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
relativeLayout = (RelativeLayout) findViewById(R.id.relLayout);
registerForContextMenu(textView);

} 25
Menus and Dialog Boxes
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
// you can set menu header with title icon etc
menu.setHeaderTitle("Choose a color");
// add menu items
menu.add(0, v.getId(), 0, "Yellow");
menu.add(0, v.getId(), 0, "Gray");
menu.add(0, v.getId(), 0, "Cyan");
}

// menu item select listener


@Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getTitle() == "Yellow") {
relativeLayout.setBackgroundColor(Color.YELLOW);
} else if (item.getTitle() == "Gray") {
relativeLayout.setBackgroundColor(Color.GRAY);
} else if (item.getTitle() == "Cyan") {
relativeLayout.setBackgroundColor(Color.CYAN);
}
return true;
}
}
26
Menus and Dialog Boxes
Popup Menu
Android Popup Menu: Android Popup Menu displays a
list of items in a vertical list which presents the view that
invoked the menu and is useful to provide an overflow of
actions related to specific content.
It displays a Menu in a popup window anchored to a View. The
popup will be shown below the anchored View if there is
room(space) otherwise above the View. If any IME(Input Method
Editor) is visible the popup will not overlap it until the View(to
which the popup is anchored) is touched. Touching outside the
popup window will dismiss it.
27
Menus and Dialog Boxes
Example:
In this example, we are going to make a popup menu anchored to
a Button and on click, the popup menu will appear, and on a touch of the
popup menu item, a Toast message will be shown. A sample GIF is given
below to get an idea about what we are going to do in this article.

Step By Step Implementation


Step 1: Create a New Project in Android Studio
To create a new project in Android Studio. The code for that has been given
in both Java Programming Language for Android.

28
Menus and Dialog Boxes
Step 2: Working with the XML Files
Next, go to the activity_main.xml file, which represents
the UI of the project. Below is the code for
the activity_main.xml file.

29
Menus and Dialog Boxes
<?xml version="1.0" encoding="utf-8"?>
I <androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<Button
android:id="@+id/clickBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#0F9D58"
android:text="Click Me"
android:textColor="#ffffff"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
30
Menus and Dialog Boxes
Before moving further let’s add some color attributes in order to enhance
the app bar. Go to app > res > values > colors.xml and add the following
color attributes.
<resources>
<color name="colorPrimary">#0F9D58</color>
<color name="colorPrimaryDark">#16E37F</color>
<color name="colorAccent">#03DAC5</color>
</resources>

31
Menus and Dialog Boxes
Step 3: Create Menu Directory and Menu file
First, we will create a menu director which will contain the menu file. Go
to app > res > right-click > New > Android Resource Directory and give
the Directory name and Resource type as menu.

32
Menus and Dialog Boxes
Now, we will create a popup_menu file inside that menu resource directory. Go
to app > res > menu > right-click > New > Menu Resource File and create a menu
resource file and name it popup_menu. In the popup_menu file, we will add menu
items. Below is the code snippet for the popup_menu.xml file.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/java"
android:title="Java" />
<item
android:id="@+id/kotlin"
android:title="Kotlin" />

33
Menus and Dialog Boxes
<item
android:id="@+id/android"
android:title="Android" />
<item
android:id="@+id/react_native"
android:title="React Native" />
</menu>

34
Menus and Dialog Boxes
Step 4: Working with the MainActivity file
In the MainActivity file, we will get the reference of the Button and initialize
it. Add onClick behavior to the button and inflate the popup menu to it.
Below is the code snippet for the MainActivity file.
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

35
Menus and Dialog Boxes
// Referencing and Initializing the button
I button = (Button) findViewById(R.id.clickBtn);

// Setting onClick behavior to the button


button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Initializing the popup menu and giving the reference as current context
PopupMenu popupMenu = new PopupMenu(MainActivity.this, button);

// Inflating popup menu from popup_menu.xml file


popupMenu.getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
// Toast message on menu item clicked
Toast.makeText(MainActivity.this, "You Clicked " + menuItem.getTitle(),
Toast.LENGTH_SHORT).show();
return true;
}
});
// Showing the popup menu
popupMenu.show();
}
});
}
}

36
Menus and Dialog Boxes
Dialog Box
A dialog box is a small box or window that prompts the user to enter
additional information or to make yes/ok or no/cancel decisions. A dialog
box is normally used for situations that require users to take an action
before they can continue. In our example, when the home icon on the
toolbar is clicked, the dialog box appears as shown below

37
Menus and Dialog Boxes
The creation of the dialog boxes is considered flexible. It can be created
using the AlertDialog Java class which existed before Android devices were
invented.
Android Alert Dialog is built with the use of three fields: Title, Message
area, and Action Button.
• Alert Dialog code has three methods:
• setTitle() method for displaying the Alert Dialog box Title
• setMessage() method for displaying the message
• setIcon() method is used to set the icon on the Alert dialog box.

Then we add the two


Buttons, setPositiveButton and setNegativeButton to our Alert Dialog Box
as shown below.

38
Menus and Dialog Boxes
Step By Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to
Create/Start a New Project in Android Studio. The code for that has been
given in both Java and Kotlin Programming Language for Android.

Step 2: Working with the XML Files


Next, go to the activity_main.xml file, which represents the UI of the
project. Below is the code for the activity_main.xml file.

39
Menus and Dialog Boxes
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="180dp"
android:gravity="center_horizontal"
android:text="Press The Back Button of Your Phone."
android:textSize="30dp"
android:textStyle="bold" />
</RelativeLayout>

40
Menus and Dialog Boxes
Step 3: Working with the MainActivity File
Go to the MainActivity File and refer to the following code. Below is the
code for the MainActivity File.
import android.content.DialogInterface;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); }
@Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Do you want to exit ?");
41
Menus and Dialog Boxes
builder.setTitle("Alert !");
builder.setCancelable(false);
builder.setPositiveButton("Yes", (DialogInterface.OnClickListener) (dialog,
which) -> {
finish();
});
builder.setNegativeButton("No", (DialogInterface.OnClickListener) (dialog,
which) -> {
dialog.cancel();
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}

42
Menus and Dialog Boxes
How to Create a Custom AlertDialog in Android
Sometimes in AlertDialog, there is a need to get input from the user or
customize it according to our requirements. So we create custom
AlertDialogs. We will show how to customize the AlertDialogs and take
input from it.

43
Menus and Dialog Boxes
Step 1: Create an XML file custom_layout.xml
Add the below code in custom_layout.xml. This code defines the alert dialog
box dimensions and adds an edit text to it.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="20dp"
android:paddingRight="20dp">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
44
Menus and Dialog Boxes
Step 2: Remove TextView and Add a Button in activity_main.xml
The button when clicked will show the AlertDialog box.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="showAlertDialogButtonClicked"
android:text="Show Dialog" />
</LinearLayout>

45
Menus and Dialog Boxes
Step 3: Add custom_layout.xml file
Add custom_layout.xml in that activity in which you want to show a custom
alert dialog here it is added in MainActivity.
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

46
Menus and Dialog Boxes
I
public void showAlertDialogButtonClicked(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Name");
final View customLayout = getLayoutInflater().inflate(R.layout.custom_layout, null);
builder.setView(customLayout);

builder.setPositiveButton("OK", (dialog, which) -> {


EditText editText = customLayout.findViewById(R.id.editText);
sendDialogDataToActivity(editText.getText().toString());
});
AlertDialog dialog = builder.create();
dialog.show();
}

private void sendDialogDataToActivity(String data) {


Toast.makeText(this, data, Toast.LENGTH_SHORT).show();
}
}

47
Menus and Dialog Boxes
I

48
Menus and Dialog Boxes
I

49
Menus and Dialog Boxes
I

50
Menus and Dialog Boxes
I

51
Menus and Dialog Boxes
I

52
Menus and Dialog Boxes
I

53
Menus and Dialog Boxes
I

54
Menus and Dialog Boxes
I

55
Menus and Dialog Boxes
T
T

56
Menus and Dialog Boxes
T
T

57
Menus and Dialog Boxes
T
T

58
Menus and Dialog Boxes
T
T

59
Menus and Dialog Boxes
T
T

60
Menus and Dialog Boxes
T
T

61
Menus and Dialog Boxes
T
T

62
Menus and Dialog Boxes
T
T

63
Menus and Dialog Boxes
T
T

64
Menus and Dialog Boxes
T
T

65
Menus and Dialog Boxes
T
T

66
Menus and Dialog Boxes
T
T

67
Menus and Dialog Boxes
T
T

68
Menus and Dialog Boxes
T
T

69
Menus and Dialog Boxes
T
T

70
Menus and Dialog Boxes
T
T

71
Menus and Dialog Boxes
T
T

72
Menus and Dialog Boxes
T
T

73
Menus and Dialog Boxes
T
T

74
Menus and Dialog Boxes
T
T

75

You might also like