Android ListView → Android ListView – ContextMenu – Camposha

Android ListView

Android ListView

Android ListView

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 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.

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.

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

Leave a Reply

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

Join Us
X