Free Education

Online Education

Android Studio

context menu in android studio example

Hello Guys. Welcome to our new tutorial of the context menu in android studio example. Here we will teach you the Android Context Menu Example.

android context menu appears for long pressing on the element. its also call ass floating menu.

please follow the code given below to use Android Context Menu Example

  • First Create a new project in Android Studio
  • File ⇒ New Android ⇒ Application Project
  • Then Open src -> package -> MainActivity.java and then add following code :

JAVA (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.Button;
import android.widget.Toast;


public class Contextmenu extends AppCompatActivity {

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

      

        Button btn = (Button) findViewById(R.id.btnShow);
        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, "Cut");
        menu.add(0, v.getId(), 0, "Copy");
        menu.add(0, v.getId(), 0, "Paste");
         }
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        Toast.makeText(this, "Selected Item: " +item.getTitle(), Toast.LENGTH_SHORT).show();
        return true;
    }
}
  •  Now Open res -> layout -> activity_main.xml and then add following code :

XML (activity_main.xml)

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btnShow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Long press me"
        app:layout_constraintBottom_toTopOf="@+id/adView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

   
</android.support.constraint.ConstraintLayout>

Output:

Finally, run this project.

This is how the context menu in android looks like

context menu in android context menu in android

Leave a Reply

Your email address will not be published. Required fields are marked *