Android ContextMenu

Android ContextMenu Tutorial and Examples.

Extension of Menu for context menus providing functionality to modify the header of the context menu.

Full ContextMenu Examples

Example 1 – ListView with ContextMenu example

Let’s start with our main activity.

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

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {      

    /** 
     * Construct the returned data 
     * @return 
     */ 
    private ArrayList<String> getData(){
        ArrayList<String> list = new ArrayList<String>();
        for (int i=0;i<6;i++){
            list.add("File"+(i+1));
        } 
        return list;
    } 
    /**
    * Our onCreate method
    */
    @Override 
    protected void onCreate(BundlesavedInstanceState){   
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        showListView (); 
    } 

    /** 
     * Set the display content of the listView 
     */ 
    private void showListView(){ 
        ListView listView = (ListView) findViewById(R.id.listview);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,getData());
        listView.setAdapter(adapter);
        this.registerForContextMenu ( listView ); //register the context menu
    } 

    /** 
     * Create context menu 
     * @param menu - Our context menu
     * @param v - Our View object
     * @param menuInfo  - Our ContextMenuInfo object
     */ 
    @Override 
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        // Set the content displayed by menu 
        menu.setHeaderTitle ( "File operation" );
        menu.setHeaderIcon(R.mipmap.ic_launcher);
        MenuInflater inflater = getMenuInflater();  
        inflater.inflate(R.menu.menu_main,menu);

    } 

    /** 
     * Set the click event of the menu item 
     */ 
    @Override 
    public boolean onContextItemSelected ( MenuItem item ) {   

        switch (item.getItemId()){
            case 1 :  
                Toast.makeText(this , "Selected copy" , Toast.LENGTH_SHORT).show();
                break; 
            case 2: 
                Toast.makeText(this,"Selected sticky", Toast.LENGTH_SHORT).show();
                break; 
            case 3 :  
                Toast.makeText(this,"Choose Cut" , Toast.LENGTH_SHORT).show();
                break; 
            case 4 :  
                Toast.makeText(this,"Selected Rename",Toast.LENGTH_SHORT. show();
                break; 
            case 5 :  
                Toast.makeText(this , "Selected Delete",Toast.LENGTH_SHORT).show();
                break; 
            case 6 :  
                break; 
        } 

        return super.onContextItemSelected(item);
    } 

} 

(b) activity_main.xml

This is the activity_main layout. We will render a ListView right here. At the root we have a RelativeLayout. Inside the RelativeLayout we have a ListView.

<RelativeLayout 
     android_layout_width="match_parent"
    android_layout_height="match_parent" android_paddingLeft="@dimen/activity_horizontal_margin"
    android_paddingRight="@dimen/activity_horizontal_margin"
    android_paddingTop="@dimen/activity_vertical_margin"
    android_paddingBottom="@dimen/activity_vertical_margin" tools_context=".MainActivity">

    <ListView
        android_layout_width="fill_parent"
        android_id="@+id/listview"
        android_layout_height="fill_parent">

    </ListView>

(c). menu.xml

Then we have also a menu with menu items.

<menu 
    
     tools_context=".MainActivity">
    <item android_id="@+id/context_menu_item1"
        android_title="Copy"
        android_orderInCategory="100"
        app_showAsAction="never" />
    <item android_id="@+id/context_menu_item2"
        android_title="sticky"
        android_orderInCategory="100"
        app_showAsAction="never" />
    <item android_id="@+id/context_menu_item3"
        android_title="Cut"
        android_orderInCategory="100"
        app_showAsAction="never" />

</menu>

2. ListView ContextMenu Open New Activity

In this full example we want to see how to show context menu in ListView. Then when a Contextmenu item is selected we show open a new activity.

[ui-tabs position=”top-left” active=”0″ theme=”default”]

[ui-tab title=”MainActivity.java”]
This is the main activity.

package com.example.ankitkumar.menuintent;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

[/ui-tab]
[ui-tab title=”ListView2Activity.java”]
Our ListView2Activity class.

package com.example.ankitkumar.menuintent;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

public class ListView2Activity extends Activity implements OnItemClickListener
{
    /** Called when the activity is first created. */

    ListView lview;
    ListViewAdapter lviewAdapter;

    private final static String name[] = {"Pushpa","Latha","Arjun","Kiran","Arnav",
            };

    private final static String number[] = {"9988778877", "9988778874","9988778844",
            "7988778877","9968778877"};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lview = (ListView) findViewById(R.id.listView2);
        lviewAdapter = new ListViewAdapter(this, name, number);

        System.out.println("adapter => "+lviewAdapter.getCount());

        lview.setAdapter(lviewAdapter);

        lview.setOnItemClickListener(this);

        registerForContextMenu(lview);
    }

    public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
        // TODO Auto-generated method stub
        Toast.makeText(this,"Title => "+name[position]+"=> n Description"+number[position], Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.setHeaderTitle("Select The Action");
        menu.add(0, v.getId(), 0, "Call");
        menu.add(0, v.getId(), 0, "Send SMS");

    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {

        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        String number1;

        try {
            number1 = number[info.position];

            if (item.getTitle() == "Call") {

                Intent callIntent = new Intent(Intent.ACTION_CALL);
                callIntent.setData(Uri.parse("tel:" + number1));
                startActivity(callIntent);

            } else if (item.getTitle() == "Send SMS") {
                Intent smsIntent = new Intent(Intent.ACTION_VIEW);
                smsIntent.setType("vnd.android-dir/mms-sms");
                smsIntent.putExtra("address", number1);
                startActivity(smsIntent);

            } else {
                return false;
            }
            return true;
        } catch (Exception e) {
            return true;
        }
    }
}

[/ui-tab]

[ui-tab title=”ListViewAdapter.java”]
Our ListViewAdapter class.

package com.example.ankitkumar.menuintent;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class ListViewAdapter extends BaseAdapter
{
    Activity context;
    String title[];
    String description[];

    public ListViewAdapter(Activity context, String[] title, String[] description) {
        super();
        this.context = context;
        this.title = title;
        this.description = description;
    }

    public ListViewAdapter(ListView2Activity listView2Activity) {

    }

    public int getCount() {
        // TODO Auto-generated method stub
        return title.length;
    }

    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }

    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    private class ViewHolder {
        TextView txtViewTitle;
        TextView txtViewDescription;
    }

    public View getView(int position, View convertView, ViewGroup parent)
    {
        // TODO Auto-generated method stub
        ViewHolder holder;
        LayoutInflater inflater =  context.getLayoutInflater();

        if (convertView == null)
        {
            convertView = inflater.inflate(R.layout.row, null);
            holder = new ViewHolder();
            holder.txtViewTitle = (TextView) convertView.findViewById(R.id.textView1);
            holder.txtViewDescription = (TextView) convertView.findViewById(R.id.textView2);
            convertView.setTag(holder);
        }
        else
        {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.txtViewTitle.setText(title[position]);
        holder.txtViewDescription.setText(description[position]);

        return convertView;
    }

}

[/ui-tab]
[ui-tab title=”activity_main.xml”]
This is the layout for the main activity. It will contain a ListView wrapped in a LinearLayout.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
              android_orientation="vertical"
              android_layout_width="fill_parent"
              android_layout_height="fill_parent">

    <ListView
        android_layout_height="wrap_content"
        android_id="@+id/listView2"
        android_layout_width="match_parent">
    </ListView>

</LinearLayout>

[/ui-tab]
[ui-tab title=”row.xml”]
This is the layout for a single item in the listview. It will be inflated into a View in the ListViewAdapter class.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    
    android_orientation="vertical"
    android_layout_width="match_parent"
    android_layout_height="match_parent">

    <TextView
        android_id="@+id/textView1"
        android_text="TextView"
        android_layout_height="wrap_content"
        android_layout_width="fill_parent"
        android_textAppearance="?android:attr/textAppearanceLarge">
    </TextView>

    <TextView
        android_text="TextView"
        android_id="@+id/textView2"
        android_layout_width="fill_parent"
        android_layout_height="wrap_content">
    </TextView>

</LinearLayout>

 

No. Location Link
1. GitHub Download
2. GitHub Browse
2. GitHub Original Creator: @AnkitKumar111

 

Share

Related Concepts

1 Example

  1. Android ListView – ContextMenu

    Android Custom ListView with Images Text and ContextMenu tutorial.

    The ListView will have a List of items. The user can then right click a given item and a contextmenu gets displayed.

     

    Concepts You will Learn from this Example

    1. What is a ListView?
    2. What is a ContextMenu?
    3. How to create a custom listview with images, text and contextmenu in android studio.
    4. How to implement a longclick listener in a listview.
    5. How to show contextmenu with menu items when a listview cardview is right-clicked.
    6. How to create a custom adapter with baseadapter.

    <!– #### What is ListView?
    {{ page.find(‘/android/listview’).contentMeta.shortcodeMeta.shortcode.section.listview_intro }}
    –>

    What is BaseAdapter?

    We need an adapter to work with a listview.

    An adapter is a class that acts as a bridge between an adapterview and the underlying data source.

    In this case we’ll use BaseAdapter.

    <!–
    {{ page.find(‘/android/baseadapter’).contentMeta.shortcodeMeta.shortcode.section.android_baseadapter_intro }}
    –>

    1. Gradle Files

    First we add dependencies in the app level build.gradle file.

    (a). Build.gradle
    • Let’s add some dependencies. Our ListView will comprise cardviews:
        apply plugin: 'com.android.application'
    
        android {
            compileSdkVersion 23
            buildToolsVersion "23.0.2"
    
            defaultConfig {
                applicationId "com.tutorials.hp.listviewcontextmenu"
                minSdkVersion 15
                targetSdkVersion 23
                versionCode 1
                versionName "1.0"
            }
            buildTypes {
                release {
                    minifyEnabled false
                    proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
                }
            }
        }
    
        dependencies {
            compile fileTree(dir: 'libs', include: ['*.jar'])
            testCompile 'junit:junit:4.12'
            compile 'com.android.support:appcompat-v7:23.2.1'
            compile 'com.android.support:design:23.2.1'
            compile 'com.android.support:cardview-v7:23.2.1'
        }

    2. Layout Files

    Let’s see our layout files. We’ll have three of them:

    1. activity_main.xml
    2. content_main.xml
    3. model.xml
    (a). activity_main.xml
    • Our template layout for main activity.
    • It will get inflated to the view for mainactivity.
    • It will contain the content_main.xml.
        <?xml version="1.0" encoding="utf-8"?>
        <android.support.design.widget.CoordinatorLayout 
            
            
            android_layout_width="match_parent"
            android_layout_height="match_parent"
            android_fitsSystemWindows="true"
            tools_context="com.tutorials.hp.listviewcontextmenu.MainActivity">
    
            <android.support.design.widget.AppBarLayout
                android_layout_width="match_parent"
                android_layout_height="wrap_content"
                android_theme="@style/AppTheme.AppBarOverlay">
    
                <android.support.v7.widget.Toolbar
                    android_id="@+id/toolbar"
                    android_layout_width="match_parent"
                    android_layout_height="?attr/actionBarSize"
                    android_background="?attr/colorPrimary"
                    app_popupTheme="@style/AppTheme.PopupOverlay" />
    
            </android.support.design.widget.AppBarLayout>
    
            <include layout="@layout/content_main" />
    
            <android.support.design.widget.FloatingActionButton
                android_id="@+id/fab"
                android_layout_width="wrap_content"
                android_layout_height="wrap_content"
                android_layout_gravity="bottom|end"
                android_layout_margin="@dimen/fab_margin"
                android_src="@android:drawable/ic_dialog_email" />
    
        </android.support.design.widget.CoordinatorLayout>
    (b). content_main.xml
    • This will hold our ListView.
    • It will get included inside the activity_main.xml.
        <?xml version="1.0" encoding="utf-8"?>
        <RelativeLayout 
            
            
            android_layout_width="match_parent"
            android_layout_height="match_parent"
            android_paddingBottom="@dimen/activity_vertical_margin"
            android_paddingLeft="@dimen/activity_horizontal_margin"
            android_paddingRight="@dimen/activity_horizontal_margin"
            android_paddingTop="@dimen/activity_vertical_margin"
            app_layout_behavior="@string/appbar_scrolling_view_behavior"
            tools_context="com.tutorials.hp.listviewcontextmenu.MainActivity"
            tools_showIn="@layout/activity_main">
    
            <ListView
                android_layout_width="wrap_content"
                android_layout_height="wrap_content"
                android_id="@+id/lv"
    
                android_layout_alignParentLeft="true"
                android_layout_alignParentStart="true" />
        </RelativeLayout>
    (c). model.xml
    • Is our custom listview row layout.
    • Will get inflated into a single row.
    • Contains a cardview with images and text.
        <?xml version="1.0" encoding="utf-8"?>
        <android.support.v7.widget.CardView 
            android_orientation="horizontal" android_layout_width="match_parent"
            
            android_layout_margin="10dp"
            card_view_cardCornerRadius="10dp"
            card_view_cardElevation="10dp"
    
            android_layout_height="wrap_content">
    
            <RelativeLayout
                android_layout_width="match_parent"
                android_layout_height="match_parent">
    
                <ImageView
                    android_layout_width="wrap_content"
                    android_layout_height="wrap_content"
                    android_id="@+id/movieImage"
                    android_padding="10dp"
                    android_src="@drawable/ghost" />
    
                <TextView
                    android_layout_width="wrap_content"
                    android_layout_height="wrap_content"
                    android_textAppearance="?android:attr/textAppearanceLarge"
                    android_text="Name"
                    android_id="@+id/nameTxt"
                    android_padding="10dp"
                    android_textColor="@color/colorAccent"
                    android_layout_below="@+id/movieImage"
                    android_layout_alignParentLeft="true"
                     />
    
                <TextView
                    android_layout_width="wrap_content"
                    android_layout_height="wrap_content"
                    android_textAppearance="?android:attr/textAppearanceLarge"
                    android_text=" John Doe a former FBI Agent and now Physics teacher .is wrongly accussed of murdering an innocent child.He makes it his business to find the bad guys who did taht.He convinces hacker Aram to join him.....
                    "
                    android_id="@+id/descTxt"
                    android_padding="10dp"
                    android_layout_below="@+id/nameTxt"
                    android_layout_alignParentLeft="true"
                    />
    
                <TextView
                    android_layout_width="wrap_content"
                    android_layout_height="wrap_content"
                    android_textAppearance="?android:attr/textAppearanceMedium"
                    android_text="TV Show"
                    android_id="@+id/posTxt"
                    android_padding="10dp"
    
                    android_layout_below="@+id/movieImage"
                    android_layout_alignParentRight="true" />
    
                <CheckBox
                    android_layout_width="wrap_content"
                    android_layout_height="wrap_content"
                    android_id="@+id/chk"
                    android_layout_alignParentRight="true"
                    />
    
            </RelativeLayout>
        </android.support.v7.widget.CardView>

    3. Java Classes

    We are using java programming language.

    We’ll have 5 classes:

    (a). Movie.java
    • Is our data object, a POJO class.
    • Represents a single movie object with various properties.
    • Each CardView will hold a movie.
        package com.tutorials.hp.listviewcontextmenu;
    
        public class Movie {
    
            private String name;
            private int image;
    
            public Movie(String name, int image) {
                this.name = name;
                this.image = image;
            }
    
            public String getName() {
                return name;
            }
    
            public int getImage() {
                return image;
            }
        }
    (b). LongClickListener
    • Is an interface.
    • Contains the signature for our LongClick listener.
        package com.tutorials.hp.listviewcontextmenu;
    
        public interface LongClickListener {
            void onItemLongClick();
        }
    (c). MyViewHolder.java
    • Our ViewHolder class.
    • Will hold views to be recycled.
    • Will implement View.OnLongClickListener and View.OnCreateContextMenuListener.
        package com.tutorials.hp.listviewcontextmenu;
    
        import android.view.ContextMenu;
        import android.view.View;
        import android.widget.ImageView;
        import android.widget.TextView;
    
        public class MyViewHolder implements View.OnLongClickListener,View.OnCreateContextMenuListener {
    
            ImageView img;
            TextView nameTxt;
            LongClickListener longClickListener;
    
            public MyViewHolder(View v) {
                img= (ImageView) v.findViewById(R.id.movieImage);
                nameTxt= (TextView) v.findViewById(R.id.nameTxt);
    
                v.setOnLongClickListener(this);
                v.setOnCreateContextMenuListener(this);
            }
    
            public void setLongClickListener(LongClickListener lc)
            {
                this.longClickListener=lc;
            }
    
            @Override
            public boolean onLongClick(View v) {
                this.longClickListener.onItemLongClick();
                return false;
            }
    
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                menu.add(0,0,0,"Share");
                menu.add(0,1,0,"Rate");
                menu.add(0,2,0,"Watch");
            }
        }
    (d). CustomAdapter.java
    • Our adapter class.
    • Derives from BaseAdapter.
    • Will adapt our data to our custom views.
        package com.tutorials.hp.listviewcontextmenu;
    
        import android.content.Context;
        import android.view.LayoutInflater;
        import android.view.MenuItem;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.BaseAdapter;
        import android.widget.Toast;
    
        import java.util.ArrayList;
    
        public class CustomAdapter extends BaseAdapter {
            Context c;
            ArrayList<Movie> movies;
            LayoutInflater inflater;
            String name;
    
            public CustomAdapter(Context c, ArrayList<Movie> movies) {
                this.c = c;
                this.movies = movies;
            }
    
            @Override
            public int getCount() {
                return movies.size();
            }
    
            @Override
            public Object getItem(int position) {
                return movies.get(position);
            }
    
            @Override
            public long getItemId(int position) {
                return position;
            }
    
            @Override
            public View getView(final int position, View convertView, ViewGroup parent) {
    
                if(inflater==null)
                {
                    inflater= (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                }
    
                if(convertView==null)
                {
                    convertView=inflater.inflate(R.layout.model,parent,false);
                }
    
                //BIND DATA TO VIEWS
                MyViewHolder holder=new MyViewHolder(convertView);
                holder.nameTxt.setText(movies.get(position).getName());
                holder.img.setImageResource(movies.get(position).getImage());
    
                holder.setLongClickListener(new LongClickListener() {
                    @Override
                    public void onItemLongClick() {
                        name=movies.get(position).getName();
                        Toast.makeText(c,name,Toast.LENGTH_SHORT).show();
                    }
                });
    
                return convertView;
            }
    
            public void getSelecetedItem(MenuItem item)
            {
                Toast.makeText(c,name+" "+item.getTitle(),Toast.LENGTH_SHORT).show();
            }
        }
    (e). MainActivity.java
    • Our MainActivity.
    • References ListView from layout.
    • Instantiates the CustomAdapter and sets it to our ListView.
        package com.tutorials.hp.listviewcontextmenu;
    
        import android.os.Bundle;
        import android.support.design.widget.FloatingActionButton;
        import android.support.design.widget.Snackbar;
        import android.support.v7.app.AppCompatActivity;
        import android.support.v7.widget.RecyclerView;
        import android.support.v7.widget.Toolbar;
        import android.view.View;
        import android.view.Menu;
        import android.view.MenuItem;
        import android.widget.AdapterView;
        import android.widget.ListView;
    
        import java.util.ArrayList;
    
        public class MainActivity extends AppCompatActivity {
    
           ListView lv;
            CustomAdapter adapter;
    
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
                Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
                setSupportActionBar(toolbar);
    
                FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
                fab.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                                .setAction("Action", null).show();
                    }
                });
    
                lv= (ListView) findViewById(R.id.lv);
                adapter=new CustomAdapter(this,getMovies());
    
                lv.setAdapter(adapter);
    
            }
    
            @Override
            public boolean onContextItemSelected(MenuItem item) {
    
                 adapter.getSelecetedItem(item);
                return super.onContextItemSelected(item);
            }
    
            private ArrayList<Movie> getMovies() {
                //COLECTION OF CRIME MOVIES
                ArrayList<Movie> movies=new ArrayList<>();
    
                Movie movie=new Movie("Shuttle Carrier",R.drawable.shuttlecarrier);
    
                //ADD ITR TO COLLECTION
                movies.add(movie);
    
                movie=new Movie("Fruits",R.drawable.fruits);
                movies.add(movie);
    
                movie=new Movie("Breaking Bad",R.drawable.breaking);
                movies.add(movie);
    
                movie=new Movie("Crisis",R.drawable.crisis);
                movies.add(movie);
    
                movie=new Movie("Ghost Rider",R.drawable.rider);
                movies.add(movie);
    
                movie=new Movie("Star Wars",R.drawable.starwars);
                movies.add(movie);
    
                movie=new Movie("BlackList",R.drawable.red);
                movies.add(movie);
    
                movie=new Movie("Men In Black",R.drawable.meninblack);
                movies.add(movie);
    
                movie=new Movie("Game Of Thrones",R.drawable.thrones);
                movies.add(movie);
    
                return movies;
    
            }
        }

    4. Download

    Hey,everything is in source code reference that is well commented and easy to understand and can be downloaded below.

    Also check our video tutorial it’s more detailed and explained in step by step.

    No. Location Link
    1. GitHub Direct Download
    2. GitHub Browse
    3. YouTube YouTube Channel



Share an Example

Share an Example

Browse
What is the capital of Egypt? ( Cairo )