How to add click event listener to context menu item in Android

In this android programming source code example, we are going to add click event listener to context menu item in Android.

You can copy and adopt this source code example to your android project without reinventing the wheel.

Below is a step by step source code to add click event listener to context menu item in Android.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ededed">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Option Menu"
        android:gravity="center"
        android:textSize="20sp"/>


    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Long Press Me"
        android:background="@color/colorAccent"
        android:textColor="#ffffff"
        android:layout_alignParentBottom="true"
        android:onClick="contexMenu"/>
</RelativeLayout>

MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.bluapp.androidview.R;

public class MenuActivity19 extends AppCompatActivity implements View.OnCreateContextMenuListener {

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

    public void contexMenu(View view){
        view.setOnCreateContextMenuListener(this);
    }

    @Override
    public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
        contextMenu.setHeaderTitle("Select The Action!");
        contextMenu.add(0, view.getId(), 0, "Delete");
        contextMenu.add(0, view.getId(), 0, "Edit");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item){
        if(item.getTitle()=="Delete"){
            Toast.makeText(MenuActivity19.this, "Delete was pressed", Toast.LENGTH_LONG).show();
        }else{
            Toast.makeText(MenuActivity19.this, "Edit was pressed", Toast.LENGTH_LONG).show();
        }
        return true;
    }
}

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.