Home »
Android
Android - Context Menu Example
In this Android Example, we are going to learn how to write code to display content menu with its options? Here, you will find all project related file like java, xml.
Submitted by Shamikh Faraz, on February 07, 2018
Here, in this Android example of Context Menu - on long press, this displays a menu which contains some options, if you click outside of displayed menu, it disappears.
1) XML File: (activity_main)
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="com.example.faraz.contextmenu_example.MainActivity">
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="66dp"
android:layout_marginTop="53dp" >
</ListView>
</android.support.constraint.ConstraintLayout>
2) Java file: (MainActivity.java)
package com.example.faraz.contextmenu_example;
import android.os.Bundle;
import android.app.Activity;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
ListView listView1;
String contacts[]={"A","B","C","D","E"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView1=(ListView)findViewById(R.id.listView1);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,contacts);
listView1.setAdapter(adapter);
// Register the ListView for Context menu
registerForContextMenu(listView1);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Select what you want to do");
menu.add(0, v.getId(), 0, "Your First Function here like call");//groupId, itemId, order, title
menu.add(0, v.getId(), 0, "Your First Function here like SMS");
}
@Override
public boolean onContextItemSelected(MenuItem item){
if(item.getTitle()=="First"){
Toast.makeText(getApplicationContext(),"your intent here",Toast.LENGTH_LONG).show();
}
else if(item.getTitle()=="Second"){
Toast.makeText(getApplicationContext(),"your intent here",Toast.LENGTH_LONG).show();
}else{
return false;
}
return true;
}
}
Output
When you press long on particular item, it shows your preset context menu.