android_learners_hub
Context Menu In Android
When user press long click on the element(View) Context menu will appear.
You can provide a context menu for any view, but they are most often used
for items in a ListView, GridView, or other view collections in which the
user can perform direct actions on each item. It offers actions that affect
a specific item or context frame in the User Interface. Extension of Menu
for context menus providing functionality to modify the header of the
context menu. It do not support shortcuts and icons for the items in
menu.
To use Context Menu we need to import following Class in MainActivity.java
file.
import android.view.ContextMenu;
To create Context menu we use
onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo
menuInfo)
{
// code to execute
}
method.
Important
We also have to register the view with context menu in onCreate(Bundle
savedInstanceState) by calling registerForContextMenu() and pass it
the View.
Example:- registerForContextMenu(list);
There are two ways to provide contextual actions:
Floating context menu | Contextual action mode |
---|---|
1. It is used when user wants to perform a contextual action on one item at a time. | 1. It is used when user want to perform an action on multiple items at once . |
2. It appears as a floating list of menu items when the user perform long-click on a view that declares support for a context menu. | 2. It appears as a contextual action bar at the top of the screen with action items (or menu item) that affect the selected item or items. |
Example | Example |
Public methods:
Methods | Description | Example |
---|---|---|
1.clearHeader() | Clears the header of the context menu. |
@Override publicvoid onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); getMenuInflater().inflate(R.menu.context_menu, menu); menu.clearHeader(); } |
2.setHeaderIcon (int iconRes) |
Sets the context menu header's icon to the icon given in iconRes resource id. |
@Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo); { ;super.onCreateContextMenu(menu, v, menuInfo); getMenuInflater().inflate(R.menu.context_menu, menu); menu.setHeaderIcon(icon); } |
3.setHeaderIcon(Drawableicon) | Sets the context menu header's icon to the icon given in icon Drawable. |
@Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); getMenuInflater().inflate(R.menu.context_menu, menu); menu.setHeaderIcon(R.drawable.icon); } |
4.setHeaderTitle (int titleRes) |
Sets the context menu header's title to the title given in titleRes
resource identifier. |
@Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); getMenuInflater().inflate(R.menu.context_menu, menu); menu.setHeaderTitle(R.string.app_name); } |
5.setHeaderTitle(CharSequence title) | Sets the context menu header's title to the title given in title. |
@Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); getMenuInflater().inflate(R.menu.context_menu, menu); menu.setHeaderTitle("Title"); } |
6.setHeaderView(Viewview) | Sets the header of the context menu to the View given in view. This replaces the header title and icon. |
@Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); getMenuInflater().inflate(R.menu.context_menu, menu); menu.setHeaderView(v); } |
How to Handle click events in Context menu?
To handle click events (by the user) we have to implement
onContextItemSelected(MenuItem item). The item that the user selected get
stored in its parameter(item). It will help to identify the specific task that
will be perform when that item is selected. The getItemId() method queries the
ID for the selected menu item, which you should assign to each menu item in
XML using the android:id attribute.You will understand better through
following example:-
@Override
// the selected menu item is stored in item
public boolean onContextItemSelected(MenuItem item) {
//if the value of item = id = edit then the following code
will execute.
switch (item.getItemId()) {
case R.id.edit:
// code to execute
return true;
//if the value of item = id = delete then the following code will execute.
case R.id.delete:
// code to execute
return true;
// if the value of selected item doesnot match with any case written
here then, default function will execute.
default:
return
super.onContextItemSelected(item);
}
With the help of following example let's see how to create Floating context
menu :-
Here we will create context menu(menu) on listview(view) similar
as we see in Contacts app . We will design a context menu that will show call
,text etc. to contacts shown in listview.
As always first create a new folder menu inside of our project resource
directory (res/menu/) and then, create a file(context_menu.xml) in it
to create menu item and sub menu.
Code for context_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/context_call"
android:title="Call" >
<menu>
<item
android:id="@+id/context_video"
android:title="Video Call" />
<item
android:id="@+id/context_voice"
android:title="Voice Call" />
</menu>
</item>
<item
android:id="@+id/context_text"
android:title="Send Text" />
<item
android:id="@+id/context_location"
android:title="Send location"/>
</menu>
Now, create App bar, Textview and Listview with the help of toolbar, textview
tag and listview tag respectively in activity_main.xml.
Code for activity_main.xml
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#C59169"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme" />
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#4FCCBD5C"
android:text="All Contacts"
android:textAlignment="center"
android:textSize="24sp"
android:textStyle="bold"
android:textColor="#FF000000"/>
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#C59169" />
</LinearLayout>
In MainActivity.java Initialize views that we created in
activity_main.xml file. To store the listitem we need to create an array and
then pass it to adapter. After that set adapter to list and then, register
the view with context menu.
Code for MainActivity.java
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.PopupMenu;
import androidx.appcompat.widget.Toolbar;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//declare the toolbar and give the toolbar the ability to have those options menu show up
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
//Referencing and Initializing List View
ListView list=findViewById(R.id.list_view);
String[] listitem={"A","Amandeep","Anchal","Ankita","Amritpreet","B","Babita","Bableen","Baby","C","Cherry","Chetan","Charanjeet"};
ArrayAdapter adapter=new ArrayAdapter(this, android.R.layout.simple_list_item_1,android.R.id.text1,listitem);
list.setAdapter(adapter);
// Referencing and Initializing text View
TextView text_pop=findViewById(R.id.text);
// registering list view for context menu
registerForContextMenu(list);
}
}
After that lets now write
code to create context menu and to handle click event. I am here using a simple Toast message to display title when the item is
selected.
// this code is written outside Oncreate(Bundle savedInstancestate) and inside class
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.context_menu, menu);
menu.setHeaderView(v);
}
@Override
public boolean onContextItemSelected(@NonNull MenuItem item) {
Toast.makeText(this, "You select : "+item.getTitle(), Toast.LENGTH_LONG).show();
return super.onContextItemSelected(item);
}
}// close brace of class MIainactivity
When you will execute above code Output will be:-
Comments
Post a Comment