Android SimpleRecyclerView Events – OnClick and OnLongClick

Android SimpleRecyclerView Events – OnClick and OnLongClick



Rating : 5/5 (2)




Android Simple RecyclerView - OnClick and OnLongClick events

Introduction

This is an android simple recyclerview tutorial. We'll see how to handle OnItemClick and OnItemLongClick events.First we populate our recyclerview with a list of data. The data will comprise of a list of Galaxy objects. Each galaxy will have a name, description as well as an image. Each galaxy object will correspond to a CardView. When the user clicks a single card, we show the name of the galaxy that is clicked, otherwise if he longClicks, we show its description.

Screenshot

  • Here's the screenshot of the project.

Android SimpleRecyclerView OnItemClick event example.

Android SimpleRecyclerView OnLongClick events

Android SimpleRecyclerView OnItemLongClick event example.

Android SimpleRecyclerView OnLongClick events

Android SimpleRecyclerView events example. : Project Structure.

Android SimpleRecyclerView events example Project Structure

Common Questions this example explores

  • Android SimpleRecylerView example.
  • Android SimpleRecyclerView itemClick and onLongClick events.
  • Handling click and longclic events in RecyclerView.
  • Android SimpleRecyclerView library.
  • Android ReccylerView with images and text.

Tools Used

This example was written with the following tools:

  • Windows 8
  • AndroidStudio IDE
  • Genymotion Emulator
  • Language : Java
  • Topic : RecyclerView Events, Android SimpleRecyclerView

Libaries Used

  • We use Android SimpleRecyclerView library.

Source Code

Lets jump directly to the source code.

Build.Gradle Project LevelBuild.Gradle App LevelGalaxy.javaGalaxyCell.javaMainActivity.javaActivityMain.xmlModel.xmlVideo/PreviewDownload
  • Our project level build.gradle.
  • We add repositories for fetching our dependencies here.
  • The dafult,jccenter() is already specified.
  • However, we add the maven and specify the url we'll use to fetch our third part library here.
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
allprojects {
    repositories {
        jcenter()
        maven { url "https://jitpack.io"}
        maven { url "https://maven.google.com" }
    }
}
task clean(type: Delete) {
    delete rootProject.buildDir
}

 

  • Our app level build.gradle file.
  • We specify compilesdk,minimum sdk,target sdk and dependencies.
  • Note that the minimum sdk for this project isn't that strict,it is much lower than that specified below.
  • We also add dependencies using 'compile' statement.
  • Our activity shall derive from the appCompatActivity to make it target earlier android versions.
  • We also specify design support library as well as CardView.
  • Add dependencies including com.github.jaychang0917:SimpleRecyclerView.
  • This is the recyclerview we will use in our project.
apply plugin: 'com.android.application'
android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "com.tutorials.hp.simplerecyclerclicks"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
    compile 'com.android.support:design:26.+'
    compile 'com.android.support:cardview-v7:26.+'
    compile 'com.github.jaychang0917:SimpleRecyclerView:1.2.0'
}

 

  • Our data object
  • We pass it data via constructor.
  • We retrieve its data via getters.
package com.tutorials.hp.simplerecyclerclicks;
public class Galaxy {
    private String name,description;
    private int image;
    public Galaxy(String name, String description, int image) {
        this.name = name;
        this.description = description;
        this.image = image;
    }
    public String getName() {
        return name;
    }
    public String getDescription() {
        return description;
    }
    public int getImage() {
        return image;
    }
}

 

  • Our galaxy cell object.
  • Derives from SimpleCell.
  • ViewItem layout is inflated here.
  • Data is also bound to views here.
  • Represents a single viewitem that will get inflated from our model layout.
  • Will comprise an inner static ViewHolder class.
  • Think of this class as the equivalence of our RecyclerView.Adapter class.
package com.tutorials.hp.simplerecyclerclicks;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.jaychang.srv.SimpleCell;
import com.jaychang.srv.SimpleViewHolder;
public class GalaxyCell extends SimpleCell<Galaxy,GalaxyCell.ViewHolder>  {
    public GalaxyCell(@NonNull Galaxy item) {
        super(item);
    }
    @Override
    protected int getLayoutRes() {
        return R.layout.model;
    }
    @NonNull
    @Override
    protected ViewHolder onCreateViewHolder(ViewGroup parent, View cellView) {
        return new ViewHolder(cellView);
    }
    @Override
    protected void onBindViewHolder(@NonNull ViewHolder viewHolder, int i, @NonNull Context context, Object o) {
        viewHolder.titleTxt.setText(getItem().getName());
        viewHolder.descTxt.setText(getItem().getDescription());
        viewHolder.img.setImageResource(getItem().getImage());
    }
    /**
     * Define your view holder, which must extend SimpleViewHolder.
     * */
    static class ViewHolder extends SimpleViewHolder {
        TextView titleTxt,descTxt;
        ImageView img;
        ViewHolder(View itemView) {
            super(itemView);
            titleTxt=itemView.findViewById(R.id.nameTxt);
            descTxt=itemView.findViewById(R.id.descTxt);
            img=itemView.findViewById(R.id.galaxyImageview);
        }
    }
}

 

  • Our MainActivity class.
  • Derives from AppCompatActivity which is a Base class for activities that use the support library action bar features.
  • Methods: onCreate().
  • Inflated From activity_main.xml using the setContentView() method.
  • The views we use are RecyclerView.
  • Reference RecyclerView from our layout specification using findViewById().
  • Instantiate adapter and set it to RecyclerView.
package com.tutorials.hp.simplerecyclerclicks;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import com.jaychang.srv.SimpleCell;
import com.jaychang.srv.SimpleRecyclerView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
    SimpleRecyclerView simpleRecyclerView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        simpleRecyclerView=findViewById(R.id.recyclerView);
        this.bindData();
    }
    /*
    - BIND DATA
    - Loop through data source creating cells.
     */
    private void bindData() {
        List<Galaxy> galaxies = getData();
        List<GalaxyCell> cells = new ArrayList<>();
        for (Galaxy Galaxy : galaxies) {
            GalaxyCell cell = new GalaxyCell(Galaxy);
            // HANDLE ONCLICK LISTENER
            cell.setOnCellClickListener2(new SimpleCell.OnCellClickListener2<GalaxyCell, GalaxyCell.ViewHolder, Galaxy>() {
                @Override
                public void onCellClicked(GalaxyCell GalaxyCell, GalaxyCell.ViewHolder viewHolder, Galaxy item) {
                    Toast.makeText(MainActivity.this, item.getName(), Toast.LENGTH_SHORT).show();
                }
            });
            //HANDLE ONLONGCLICK
            cell.setOnCellLongClickListener2(new SimpleCell.OnCellLongClickListener2<GalaxyCell, GalaxyCell.ViewHolder, Galaxy>() {
                @Override
                public void onCellLongClicked(GalaxyCell GalaxyCell, GalaxyCell.ViewHolder viewHolder, Galaxy item) {
                    Toast.makeText(MainActivity.this, item.getDescription(), Toast.LENGTH_SHORT).show();
                }
            });
            //ADD CELL
            cells.add(cell);
        }
    simpleRecyclerView.addCells(cells);
    }
    /*
    - Data Source
     */
    private ArrayList<Galaxy> getData()
    {
        ArrayList<Galaxy> galaxies=new ArrayList<>();
        Galaxy g=new Galaxy("Whirlpool",
                "The Whirlpool Galaxy, also known as Messier 51a, M51a, and NGC 5194, is an interacting grand-design spiral Galaxy with a Seyfert 2 active galactic nucleus in the constellation Canes Venatici.",
                R.drawable.whirlpool);
        galaxies.add(g);
        g=new Galaxy("Triangulumn",
                "The Triangulum Galaxy is a spiral Galaxy approximately 3 million light-years from Earth in the constellation Triangulum",
                R.drawable.triangulum);
        galaxies.add(g);
        g=new Galaxy("Milky Way",
                "The Milky Way is the Galaxy that contains our Solar System." +
                        " The descriptive milky is derived from the appearance from Earth of the Galaxy – a band of light seen in the night sky formed from stars",
                R.drawable.milkyway);
        galaxies.add(g);
        g=new Galaxy("Andromeda",
                "The Andromeda Galaxy, also known as Messier 31, M31, or NGC 224, is a spiral Galaxy approximately 780 kiloparsecs from Earth. It is the nearest major Galaxy to the Milky Way and was often referred to as the Great Andromeda Nebula in older texts.",
                R.drawable.andromeda);
        galaxies.add(g);
        g=new Galaxy("Messier 81",
                "Messier 81 is a spiral Galaxy about 12 million light-years away in the constellation Ursa Major. Due to its proximity to Earth, large size and active galactic nucleus, Messier 81 has been studied extensively by professional astronomers.",
                R.drawable.messier81);
        galaxies.add(g);
        g=new Galaxy("Cosmos Redshift",
                "Cosmos Redshift 7 is a high-redshift Lyman-alpha emitter Galaxy, in the constellation Sextans, about 12.9 billion light travel distance years from Earth, reported to contain the first stars —formed ",
                R.drawable.cosmosredshift);
        galaxies.add(g);
        g=new Galaxy("StarBust",
                "A starburst Galaxy is a Galaxy undergoing an exceptionally high rate of star formation, as compared to the long-term average rate of star formation in the Galaxy or the star formation rate observed in most other galaxies. ",
                R.drawable.starbust);
        galaxies.add(g);
        g=new Galaxy("Sombrero",
                "Sombrero Galaxy is an unbarred spiral galaxy in the constellation Virgo located 31 million light-years from Earth. The galaxy has a diameter of approximately 50,000 light-years, 30% the size of the Milky Way.",
                R.drawable.sombrero);
        galaxies.add(g);
        g=new Galaxy("Pinwheel",
                "The Pinwheel Galaxy is a face-on spiral galaxy distanced 21 million light-years away from earth in the constellation Ursa Major. ",
                R.drawable.pinwheel);
        galaxies.add(g);
        g=new Galaxy("Canis Majos Overdensity",
                "The Canis Major Dwarf Galaxy or Canis Major Overdensity is a disputed dwarf irregular galaxy in the Local Group, located in the same part of the sky as the constellation Canis Major. ",
                R.drawable.canismajoroverdensity);
        galaxies.add(g);
        return galaxies;
    }
    }
  • ActivityMain.xml.
  • Our activity_mai.xml file.
  • Will get inflated to our MainActivity.
  • Contains a SimpleRecyclerView.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.tutorials.hp.simplerecyclerclicks.MainActivity">
    <com.jaychang.srv.SimpleRecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:srv_layoutMode="linearVertical"
        app:srv_showDivider="true"
        app:srv_showLastDivider="true"
        app:srv_dividerOrientation="both"
        app:srv_dividerColor="@color/colorAccent"
        app:srv_dividerPaddingLeft="5dp"
        app:srv_dividerPaddingRight="5dp"
        app:srv_dividerPaddingTop="5dp"
        app:srv_dividerPaddingBottom="5dp" />
</android.support.constraint.ConstraintLayout>

 

  • As the name suggests, this layout models our viewitem.
  • We define how each Card shall appear in our List.
  • So at the root level we have a CardView widget.
  • We can also customize our CardView by specifying cardCornerRadius,cardElevation,width,height etc.
  • Each Card shall comprise textviews and images.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_margin="5dp"
    card_view:cardCornerRadius="15dp"
    card_view:cardElevation="10dp"
    android:layout_height="200dp">
    <LinearLayout
       android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="Galaxy"
            android:id="@+id/nameTxt"
            android:padding="10dp"
      android:textColor="@color/abc_btn_colored_borderless_text_material"
            android:layout_alignParentTop="true"/>
        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <ImageView
                android:id="@+id/galaxyImageview"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"
                android:layout_marginLeft="24dp"
                android:src="@drawable/andromeda" />
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:text="Description"
                android:id="@+id/descTxt"
                android:padding="10dp"/>
        </LinearLayout>
    </LinearLayout>
</android.support.v7.widget.CardView>

 

  • We have a YouTube channel with almost a thousand tutorials, this one below being one of them.

Android S1E16 : SimpleRecyclerView - Click and LongClick Events

  • You can Download the full Project below. Source code is well commented.
Download

How To Run

  1. Download the project above.
  2. You'll get a zipped file,extract it.
  3. Open the Android Studio.
  4. Now close, already open project.
  5. From the Menu bar click on File >New> Import Project.
  6. Now Choose a Destination Folder, from where you want to import project.
  7. Choose an Android Project.
  8. Now Click on “OK“.
  9. Done, your done importing the project,now edit it.

More

YouTube

  • Visit our channel for more examples like these.

Facebook

Oclemy,Cheers.



Rating :

    Leave a Reply

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

    3 × 4 =

    COMMENTS