Context Menu Android

The menu in Android can be of three types, mainly, Option menu, Context Menu, and Popup menu. On pressing a long click on an element, the Android context menu appears which is also known as the floating menu. While acting, the context menu affects the selected content. The item shortcuts and icons are not supported by the Android Context menu.

Android Context Menu Example:

In the below example, we are demonstrating the use of the context menu in android.

activity_main.xml:

In the activity_main.xml file, we will drag a listview from the palette.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Long press button"
        android:layout_marginTop="200dp" android:layout_marginLeft="100dp"/>
</LinearLayout>

Activity class:(File: MainActivity.java)

In the MainActivity.java file, we will write the code to display the context menu on the press of the listview.

package com.example.radioapp;
 
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.Button;
import android.widget.Toast;
 
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn=findViewById(R.id.button);
        registerForContextMenu(btn);
    }
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.setHeaderTitle("Context Menu");
        menu.add(0, v.getId(), 0, "A");
        menu.add(0, v.getId(), 0, "B");
        menu.add(0, v.getId(), 0, "C");
        menu.add(0, v.getId(), 0, "D");
    }
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        Toast.makeText(this, "Selected Item: " +item.getTitle(), Toast.LENGTH_SHORT).show();
        return true;
    }
}

Output 1:

Output 2:

Content Protection by DMCA.com
Please Share