How to create a custom context menu in Android

In this android programming source code example, we are going to create a custom context menu 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 create a custom context menu 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.annotation.SuppressLint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.view.menu.MenuBuilder;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.View;

import com.bluapp.androidview.R;

public class MenuActivity20 extends AppCompatActivity implements View.OnCreateContextMenuListener {

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

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

    @Override
    public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
       super.onCreateContextMenu(contextMenu, view, contextMenuInfo);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.option_menu, contextMenu);
    }
}

menu\option_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_home"
        android:title="@string/home"
        android:orderInCategory="100"
        app:showAsAction="never" />

    <item
        android:id="@+id/action_blog"
        android:title="@string/blog"
        android:orderInCategory="100"
        app:showAsAction="never" />

    <item
        android:id="@+id/action_App"
        android:title="@string/App"
        android:orderInCategory="100"
        app:showAsAction="never" />
</menu>

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