Context Menu

Android Context Menu is a floating menu only appears when user click for a long time on an element and useful for elements that effect the selected content or context frame. To make a floating context menu, you need to follow the following steps:

  • Register the View to which the context menu should be associated by calling registerForContextMenu() and pass it the View. If your activity uses a ListView or GridView and you want each item to provide the same context menu, you can register your all items for a context menu by passing the ListView or GridView object to registerForContextMenu() method.
  • Implement the onCreateContextMenu() method in your Activity.

When the registered view receives a long-click event, the system calls your onCreateContextMenu() method. This is where you define the menu items, usually by inflating a menu resource.

Let's start creating project and try to understand, first we will create res/menu/context_menu.xml as:

res/menu/context_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/ctxMnuCopy"
        android:title="Copy" />

    <item
        android:id="@+id/ctxMnuPaste"
        android:title="Paste" />

    <item
        android:id="@+id/ctxMnuDelete"
        android:title="Delete" />

</menu>

Now create ContextMenuAdapter.java
package com.theitbulls.contextmenuex;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.recyclerview.widget.RecyclerView;

public class ContextMenuAdapter extends RecyclerView.Adapter {
    private final String[] items;
    private int position;

    public ContextMenuAdapter(String[] items) {
        this.items = items;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_view_item, parent, false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {
        final MyViewHolder viewHolder = (MyViewHolder) holder;

        viewHolder.tvName.setText(items[position]);
        viewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                setPosition(position);
                viewHolder.itemView.showContextMenu();
                return true;
            }
        });
    }

    @Override
    public void onViewRecycled(RecyclerView.ViewHolder holder) {
        holder.itemView.setOnLongClickListener(null);
        super.onViewRecycled(holder);
    }

    @Override
    public int getItemCount() {
        return items.length;
    }

    public int getPosition() {
        return position;
    }

    public void setPosition(int position) {
        this.position = position;
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public final AppCompatTextView tvName;
        public final AppCompatTextView tvMnu;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);

            tvName = itemView.findViewById(R.id.tvName);
            tvMnu = itemView.findViewById(R.id.tvMnu);
        }
    }
}


Now create ContextMenuActivity.java
package com.theitbulls.contextmenuex;

import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class ContextMenuActivity extends AppCompatActivity {
    public static final String[] values = new String[]{"Mango", "Orange", "Apple", "Grapes", "Papaya"};
    private RecyclerView rvListView;

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

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        rvListView = findViewById(R.id.recyclerListView);
        rvListView.setLayoutManager(layoutManager);
        rvListView.setAdapter(new ContextMenuAdapter(values));

        registerForContextMenu(rvListView);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        unregisterForContextMenu(rvListView);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);

        getMenuInflater().inflate(R.menu.context_menu, menu);
    }

    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
        int position = ((ContextMenuAdapter)rvListView.getAdapter()).getPosition();
        switch (item.getItemId()) {
            case R.id.ctxMnuCopy:
                Toast.makeText(this, "You select Copy for: " + values[position], Toast.LENGTH_SHORT).show();
                return true;
            case R.id.ctxMnuPaste:
                Toast.makeText(this, "You select Paste for: " + values[position], Toast.LENGTH_SHORT).show();
                return true;
            case R.id.ctxMnuDelete:
                Toast.makeText(this, "You select Delete for: " + values[position], Toast.LENGTH_SHORT).show();
                return true;
        }

        return super.onContextItemSelected(item);
    }
}


You can also create ContextMenu in MyViewHolder.java as:

public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener{
    public final AppCompatTextView tvName;
    public final AppCompatTextView tvMnu;

    public View itemView;

    public MyViewHolder(@NonNull View itemView) {
        super(itemView);

        tvName = itemView.findViewById(R.id.tvName);
        tvMnu = itemView.findViewById(R.id.tvMnu);
        this.itemView = itemView;

        itemView.setOnCreateContextMenuListener(this);
    }

    @Override
    public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
        contextMenu.add(Menu.NONE, R.id.ctxMnuCopy, Menu.NONE, "Copy"); //groupId, itemId, order, title
        contextMenu.add(Menu.NONE, R.id.ctxMnuPaste, Menu.NONE, "Paste"); //groupId, itemId, order, title
        contextMenu.add(Menu.NONE, R.id.ctxMnuDelete, Menu.NONE, "Delete"); //groupId, itemId, order, title
    }
}


Note: If you create ContextMenu in MyViewHolder.java than you must remove following code snippet from ContextMenuActivity.java otherwise menus will added twice:

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);

    getMenuInflater().inflate(R.menu.context_menu, menu);
}


Download: Context Menu & Popup Menu Example