Home > Recyclerview on Item Click Listener

Recyclerview on Item Click Listener

This tutorial explain how implement Recyclerview setOnItemListener in android application.

Creating Android Project

Step 1. Create a new project in Android Studio from File => New Project and fill the project details.


Step 2. Open build.gradle add "recyclerview" & "cardview" library after adding click on Sync Now.

	
apply plugin: 'com.android.application' android { compileSdkVersion 26 buildToolsVersion "26.0.2" defaultConfig { applicationId "com.amisun.recyclerviewclicklistner" minSdkVersion 15 targetSdkVersion 26 versionCode 1 versionName "1.0" } 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:recyclerview-v7:26.+' compile 'com.android.support:cardview-v7:26.+' }

Step 3. Now open main_activity.xml add the RecyclerView like as below.

	
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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.amisun.loadmorerecyclerview.MainActivity"> <android.support.v7.widget.RecyclerView android:id="@+id/mRecyclerview" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout>

Step 4. Now create a new recycler_view_item_row.xml file under res => layout and modified layout as below.

	
<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:card_view="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" card_view:cardUseCompatPadding="true" android:layout_margin="4dip"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:padding="10dp" android:orientation="vertical"> <TextView android:id="@+id/txtEmail" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="@android:color/black" android:textSize="16sp" android:text="Email Address" android:textStyle="bold" /> <TextView android:id="@+id/txtPhone" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="@android:color/black" android:text="9891952466" android:textSize="12sp" /> </LinearLayout> </android.support.v7.widget.CardView>

Step 5. Now create a new RecyclerView adapter class. In my case named RecyclerViewAdapter.java and modified adapter class as below.

	
package com.amisun.recyclerviewclicklistner; /** * Created by qr on 25-Oct-17. */ import android.app.Activity; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; import java.util.HashMap; public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{ private ArrayList<HashMap<String,String>> mDataset; private Context mcontext; private Activity mactivity; private OnItemClickListener listener; public interface OnItemClickListener { void onItemClick(HashMap<String, String> item); } public void add(int position, HashMap<String,String> item) { mDataset.add(position, item); notifyItemInserted(position); } public void remove( HashMap<String,String> item) { int position = mDataset.indexOf(item); mDataset.remove(position); notifyItemRemoved(position); } // Provide a suitable constructor (depends on the kind of dataset) public RecyclerViewAdapter(Context context, ArrayList<HashMap<String, String>> myDataset, RecyclerView recyclerView) { mcontext = context; mactivity = (Activity)context; mDataset = myDataset; } // Create new views (invoked by the layout manager) @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // create a new view View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_view_item_row, parent, false); // set the view's size, margins, paddings and layout parameters ViewHolderRow vh = new ViewHolderRow(v); return vh; } // Replace the contents of a view (invoked by the layout manager) @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { // - get element from your dataset at this position // - replace the contents of the view with that element HashMap map = mDataset.get(position); ViewHolderRow userViewHolder = (ViewHolderRow) holder; userViewHolder.txtEmail.setText(map.get("KEY_EMAIL")); userViewHolder.txtPhone.setText(map.get("KEY_PHONE")); //userViewHolder.email.setText(contact.getPhone()); // binding item click listner userViewHolder.bind(mDataset.get(position), listener); } // Return the size of your dataset (invoked by the layout manager) @Override public int getItemCount() { return mDataset == null ? 0 : mDataset.size(); } public void setOnItemListener(OnItemClickListener listener) { this.listener = listener; } // Provide a reference to the views for each data item // Complex data items may need more than one view per item, and // you provide access to all the views for a data item in a view holder public class ViewHolderRow extends RecyclerView.ViewHolder { public TextView txtEmail, txtPhone; public ViewHolderRow(View v) { super(v); txtEmail = (TextView)v.findViewById(R.id.txtEmail); txtPhone = (TextView)v.findViewById(R.id.txtPhone); } public void bind(final HashMap<String,String> item, final OnItemClickListener listener) { itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { listener.onItemClick(item); } }); } } }


Step 6. Now open MainActivity.java class file and modified as below.

package com.amisun.recyclerviewclicklistner; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.widget.Toast; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; public class MainActivity extends AppCompatActivity { ArrayList<HashMap<String,String>> getDatalist; private RecyclerView mrecyclerView; RecyclerViewAdapter mAdapter; private Random random; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); random = new Random(); getDatalist = new ArrayList<>(); for(int aind = 0 ; aind < 20; aind++){ HashMap<String,String> map = new HashMap<>(); map.put("KEY_EMAIL","android" + aind + "@gmail.com"); map.put("KEY_PHONE",phoneNumberGenerating()); getDatalist.add(map); } mrecyclerView = (RecyclerView) findViewById(R.id.mRecyclerview); mrecyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL, false)); mAdapter = new RecyclerViewAdapter(MainActivity.this, getDatalist, mrecyclerView); mrecyclerView.setAdapter(mAdapter); // set RecyclerView on item click listner mAdapter.setOnItemListener(new RecyclerViewAdapter.OnItemClickListener() { @Override public void onItemClick(HashMap<String, String> item) { String mEmail = ""; String mPhone = ""; try{ mEmail = item.get("KEY_EMAIL"); mPhone = item.get("KEY_PHONE"); }catch (Exception ev){ System.out.print(ev.getMessage()); } Toast.makeText(MainActivity.this,"Clicked row: \nEmail: "+mEmail+", Phone: "+mPhone,Toast.LENGTH_LONG).show(); } }); } private String phoneNumberGenerating() { int low = 100000000; int high = 999999999; int randomNumber = random.nextInt(high - low) + low; return "0" + randomNumber; } }

5. Run your application Output as below.


Dheerendra Singh

Dheerendra Singh is a Mobile Developer(Android) & Web Developer(PHP) of Amisun IT Solutions, Master degree in Computer Science.


About Us

Amisun IT Solutions is an expert Software Development Company giving complete IT arrangements and going about as a seaward improvement community for abroad advancement firms.

We are an imaginative organization, situated in India that gives a progression of Web-based programming applications that have helped clients make fruitful online activities.

Our group of forward masterminds and reforming individuals tries to furnish you with the best of arrangements with flawlessness second to none. Our key concentration is dependably to furnish you with solid arrangements which are precisely planned and planned with stringent quality principles. ...   

Read more

Address

Shoppers Square Mall Shop No. 17 & 18, First Floor,
Shoppers Square Mall, Budhh Prakash Garg Marg, Block 14, Sector 10,
Raj Nagar, Ghaziabad, Uttar Pradesh 201002
P: (+91) 9899776200, (+91) 9899773200