Context Menu in Android with Example

In Android, there are three types of menus available to define a set of options and actions in the Android apps. The lists of menus in Android applications are the following:

  1. Android options menu
  2. Android context menu
  3. Android popup menu

Here in this article let’s discuss the detail of Context Menu. In Android, the context menu is like a floating menu and arises when the user has long pressed or clicks 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. Note that we are going to implement this project using the Java language. A sample GIF is given below to get an idea about what we are going to do in this article.

Example

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.



Step 2: Working with the activity_main.xml file

Open res -> Layout -> activity_main.xml and write the following code. In this file add only a TextView to display a simple text.

XML

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Step 3: Working with the Mainactivity.java file

Open the app -> Java -> Package -> Mainactivity.java file. In this step, add the code to show the ContextMenu. Whenever the app will strat 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. 

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

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);
  
        // Link those objects with their respective id's
        // that we have given in .XML file
        textView = (TextView) findViewById(R.id.textView);
        relativeLayout = (RelativeLayout) findViewById(R.id.relLayout);
  
        // here you have to register a view for context menu
        // you can register any view like listview, image view,
        // textview, button etc
        registerForContextMenu(textView);
  
    }
  
    @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;
    }
}

chevron_right


Output: Run on Emulator

Now connect the device with a USB cable or in an Emulator and launch the application. The user will see a text. Now long pressing on the text will generate menu options and select one of them to perform specific functionality.


Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.