Android RecyclerView → Android RecyclerView – Images Text – Handle ItemClicks – Camposha

Android RecyclerView

Android RecyclerView

Android RecyclerView

Android RecyclerView – Images Text – Handle ItemClicks

 

Hey guys.In this tutorial we look at how to display images and text in a RecyclerView then handle ItemClicks.

  • First we populate images and text from an arraylist to our RecyclerView.
  • We’ll have a few classes : MyHolder tha extends RecyclerView.ViewHolder class.Its going to hold our imageview and textview for recycling.
  • Our MyAdapter class is going to derive from RecyclerView.Adapter and its going to adapt our data to our views.
  • The full source code is above for download.

===

Android RecyclerView Images Text

How to Run

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

Our Gradle Scripts

There are two build.gradle files in our android studio project :

Build.Gradle (Project)

  • Our project level build.gradle, here we have jcenter as our repository.
// 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:1.5.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Build.Gradle (App)

  • Here we add some of the dependencies we shall be using.
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'
    compile 'com.android.support:recyclerview-v7:23.2.1'
}

Our Layouts

ActivityMain.xml

  • To hold our ContentMain xml layout.
<?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.recylcerviewclick.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>

ContentMain.xml

  • Our Activity’s Content Layout.
  • Shall have our RecyclerView.
<?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.recylcerviewclick.MainActivity"
    tools:showIn="@layout/activity_main">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/myRecycler"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        class="android.support.v7.widget.RecyclerView" />
</RelativeLayout>

Model.xml

  • Our model layout.
  • We inflate this to our RecyclerView viewitems.
  • At the root we have a CardView.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView 
    android:orientation="horizontal" android:layout_width="match_parent"
    
    android:layout_margin="5dp"
    card_view:cardCornerRadius="10dp"
    card_view:cardElevation="5dp"
    android_layout_height="match_parent">
    <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/playerImage"
            android:padding="10dp"
            android:src="@drawable/herera" />
        <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:layout_alignParentTop="true"
            android:layout_toRightOf="@+id/playerImage" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="Position"
            android:id="@+id/posTxt"
            android:padding="10dp"
            android:layout_alignBottom="@+id/playerImage"
            android:layout_alignParentRight="true" />
    </RelativeLayout>
</android.support.v7.widget.CardView>

Our Classes

We have these classes and interfaces :

ItemClickListener Interface

  • ItemClick Listener interface.
  • Contains one abstract method method onItemClick().
package com.tutorials.hp.recylcerviewclick;

import android.view.View;
public interface ItemClickListener {
    void onItemClick(View v,int pos);
}

MyHolder

  • Our ViewHolder class.
  • Extends RecyclerView.ViewHolder.
  • Shall hold our TextView and ImageView.
  • Implements View.OnClickListener.
package com.tutorials.hp.recylcerviewclick;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
/**
 * OUR HOLDER CLASS
 */
public class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    //VIEWS
    ImageView img;
    TextView nameTxt;
    TextView posTxt;
    ItemClickListener itemClickListener;
    public MyHolder(View itemView) {
        super(itemView);
        //ASSIGNING VIEWS
        img= (ImageView) itemView.findViewById(R.id.playerImage);
        nameTxt= (TextView) itemView.findViewById(R.id.nameTxt);
        posTxt= (TextView) itemView.findViewById(R.id.posTxt);
        itemView.setOnClickListener(this);
    }
    //WHEN CLICKED
    @Override
    public void onClick(View v) {
        this.itemClickListener.onItemClick(v,getLayoutPosition());
    }

    //SHALL BE CALLED OUTSIDE
    public void serItemClickListener(ItemClickListener ic)

    {
        this.itemClickListener=ic;
    }
}

MyAdapter

  • To adapt our dataset to the corresponding views.
  • We inflate our Model.xml layout here.
package com.tutorials.hp.recylcerviewclick;
import android.content.Context;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class MyAdapter extends RecyclerView.Adapter<MyHolder> {
    //PROPERTIES
    Context c;
    String[] players;
    String[] positions;
    int[] imgs;

    //CONSTRUCTOR
    public MyAdapter(Context ctx,String[] names,String[] positions,int[] images)

    {
        //ASSIGN THEM AFTER BEING PASSED IN
        this.c=ctx;
        this.players=names;
        this.positions=positions;
        this.imgs=images;
    }

    //WHEN VIEWHOLDER IS BEING CREATED
    @Override
    public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //INFLATE XML AND HOLD IN VIEW
        View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.model,null);
        //HOLDER
        MyHolder holder=new MyHolder(v);
        return holder;
    }

    //DATA IS BOUND TO VIEWS
    @Override
    public void onBindViewHolder(MyHolder holder, final int position) {
        holder.img.setImageResource(imgs[position]);
        holder.nameTxt.setText(players[position]);
        holder.posTxt.setText(positions[position]);
        //SET THE ITEM CLICK LISTENER
        holder.serItemClickListener(new ItemClickListener() {
            @Override
            public void onItemClick(View v, int pos) {
                Snackbar.make(v,players[position]+" : "+positions[position],Snackbar.LENGTH_SHORT).show();
            }

        });

    }
    //TOTAL NUM OF ITEMS
    @Override
    public int getItemCount() {
        return players.length;
    }
}

MainActivity

  • Our launcher activity.
  • We have a simple array that acts as our data source.
  • We reference our RecyclerView from xml layout by its id.
  • We then set its layout manager as well as its adapter.
package com.tutorials.hp.recylcerviewclick;
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.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
    //DATA SOURCE
    String[] names={"Ander Herera","David De Gea","Michael Carrick","Juan Mata","Diego Costa","Oscar"};
    String[] positions={"Midfielder","GoalKeeper", "Midfielder","Playmaker","Striker","Playmaker"};
    int[] images={R.drawable.herera,R.drawable.degea,R.drawable.carrick,R.drawable.mata,R.drawable.costa,R.drawable.oscar};
    @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();
            }
        });
        //GET RECYCLER
        RecyclerView rv= (RecyclerView) findViewById(R.id.myRecycler);
        //SET LAYOUT
        rv.setLayoutManager(new LinearLayoutManager(this));
        rv.setItemAnimator(new DefaultItemAnimator());
        //ADAPTER
        MyAdapter adapter=new MyAdapter(this,names,positions,images);
        rv.setAdapter(adapter);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

More

YouTube

Facebook

Oclemy,Cheers.

Leave a Reply

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

Join Us
X