Open In App

Context Menu in Android with Example

Last Updated : 10 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Android, there are three types of menus available to define a set of options and actions in the Android apps. Here in this article let’s 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.

A sample GIF is given below to get an idea about what we are going to do in this article.

ContextMenu-(1)-(1)

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.

activity_main.xml:

XML
<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"
    android:background="@color/white"
    android:id="@+id/main"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Long press me!"
        android:textSize="20sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.4" />

</androidx.constraintlayout.widget.ConstraintLayout>

Design UI:

Layout_1


Step 3: Working with the MainActivity file

Open the app > Java > Package > Mainactivity.kt 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. 

MainActivity File:

Java
package org.geeksforgeeks.demo;

import android.graphics.Color;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

public class MainActivity extends AppCompatActivity {

    private TextView textView;
    private ConstraintLayout layout;

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

        // Link objects with their respective IDs from the XML file
        textView = findViewById(R.id.textView);
        layout = findViewById(R.id.main);

        // Register a view for the context menu
        registerForContextMenu(textView);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        // Set menu header title
        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");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        String title = item.getTitle().toString();

        switch (title) {
            case "Yellow":
                layout.setBackgroundColor(Color.YELLOW);
                break;
            case "Gray":
                layout.setBackgroundColor(Color.GRAY);
                break;
            case "Cyan":
                layout.setBackgroundColor(Color.CYAN);
                break;
        }
        return true;
    }
}
Kotlin
package org.geeksforgeeks.demo

import android.graphics.Color
import android.os.Bundle
import android.view.ContextMenu
import android.view.ContextMenu.ContextMenuInfo
import android.view.MenuItem
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout

class MainActivity : AppCompatActivity() {
    private lateinit var textView: TextView
    private lateinit var layout: ConstraintLayout

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Link those objects with their respective
        // id's that we have given in .XML file
        textView = findViewById(R.id.textView)
        layout = findViewById(R.id.main)

        // 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 fun onCreateContextMenu(menu: ContextMenu, v: View, menuInfo: ContextMenuInfo?) {
        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.id, 0, "Yellow")
        menu.add(0, v.id, 0, "Gray")
        menu.add(0, v.id, 0, "Cyan")
    }


    // menu item select listener
    override fun onContextItemSelected(item: MenuItem): Boolean {
        if (item.title === "Yellow")
            layout.setBackgroundColor(Color.YELLOW)
        
        else if (item.title === "Gray")
            layout.setBackgroundColor(Color.GRAY)

        else if (item.title === "Cyan")
            layout.setBackgroundColor(Color.CYAN)

        return true
    }
}

Output:

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.




Next Article

Similar Reads