Adv

Android RecyclerView

Android RecyclerView Tutorial and Examples

This is an android recyclerview tutorial. We see what a recyclerview is, why we need it and several examples of how to apply it.

What is a RecyclerView?

A RecyclerView is an adapterview that allows us display a large data set through just a limited window.

RecyclerViews were introduced in Android API 5 as an alternative to ListViews. ListView as you may already know is also an adapterview and allows us display items in a vertically scrolling list.

The term RecyclerView comes from a combination of two words: Recycler and View.

The term Recycler comes from the verb recycle which means to treat things that have already been used so that they can be used again if Oxford Advanced Learner’s Dictionary* is to be believed.

Collins Cobuild English Dictionary tells us that a view refers to the way in which a piece of text or graphics is displayed on a computer screen.

And to be honest those two terms in a way defines us exactly what a RecyclerView is. In that a RecyclerView recycles views. It reuses views. And those views are just pieces of grahpical user interface widgets that normally we define in XML and get inflated in java.

RecyclerViews are not limited to any one particular view. Instead it can utilize any. Be it TextViews, Buttons, checkBoxes etc.

RecyclerView is meant to work as an adapterview, basically with an adapter that adapts data to the RecyclerView’s views. AdapterViews normally display collections of data.

Even though there have been various great and popular adapterviews like ListViews, GridViews and expandablelistviews, recyclerview is the best when it comes to displaying large quantities of data.

And that’s because of it’s concept of recycling already used views instead of re-inflating them everytime.

Infation of views is normally expensive as it involves parsing of XML layouts into java objects. And remember this is to be done in realtime as the user scrolls through a list of data. Users can definitely notice that. And you can imagine having hundreds of rows or grids of data. Not so good isn’t it?

So RecyclerView is great in this regard as instead of re-inflating the views, it holds them in a ViewHolder class and then recycles them, only binding fresh data to them. The end result is smoothness even with large datasets that we and our users can take for granted.

Advantages of RecyclerViews
No. Advantage Description
1. Efficient. Android Engineers introduced RecyclerViews to provide a more efficient way of displaying large data sets. Previously ListViews were and gridviews were the only inbuilt alternatives. They are great for small data sets but not for large.
2. Flexible RecyclerViews are the most flexible adapterviews in android. I have seen people using them to build almost anything from creating input forms to scrollable grids to other adapterviews.
3. Easy to use. This is one of the reasons why they are popular. Some may argue that you always need two or three classes however, these are simple classes that can be combined in one file.
4. Obeys SOC(Seperation of Concerns) A RecyclerView decouples adapter from views. Hence we can work on either without touching the other.
Programmatic Definition of RecyclerViews

Like anything you can imagine in android or even java at large, a RecyclerView is just a class:

class RecyclerView{..} 

This clas is defined in a package:

package android.support.v7.widget;

And is public so that it’s not only visible to class in this package but also those in other packages:

public class RecyclerView{..} 

RecyclerView extends android.view.ViewGroup. ViewGroup is a special view that can contain other views. It can basically hold children within itself. Think of views like relativelayout and linearlayout.

public class RecyclerView extends ViewGroup... {..}

This will give a RecyclerView the capability to hold views as well.

Then RecyclerView implements two interfaces:

public class RecyclerView extends ViewGroup implements ScrollingView, NestedScrollingChild{..}
  1. ScrollingView – An interface housed in the android.support.v4.view package. It provides scroll related APIs to RecyclerView. These includes APIs such as computeHorizontalScrollExtent(),computeVerticalScrollExtent() etc.
  2. NestedScrollingChild – Also belongs to
    android.support.v4.view and provides support for dispatching of nested scrolling operations to a cooperating parent ViewGroup.

1 : Android RecyclerView – Fill With Array

[center] Android RecyclerView Tutorial – How to fill a recyclerview from an array. [/center]

This is a simple RecyclerView tutorial.Here is what we do:

  • Fill RecyclerView with data from a simple Array.
  • We derive from RecycelView.ViewHolder to get our custom viewholder class.
  • We aslo derive from RecyclerView.Adapter to get our adapter class that helps us bind our data to our RecyclerView.
  • We create a model layout using cardview that’s inflated to a view item for our recyclerview.
What this Example Teaches Us
  1. How to populate a recyclerview with an array.
  2. How to render cardviews in a recyclerview.
(a). Our View Holder Class
  • Holds our views for recycling.
package com.tutorials.hp.recyclerviewarray;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

public class MyViewHolder extends RecyclerView.ViewHolder {

    TextView nameTxt;

    public MyViewHolder(View itemView) {
        super(itemView);

        nameTxt = (TextView) itemView.findViewById(R.id.nameTxt);

    }

}
(b). Our Adapter Class
  • Responisble for layout inflation.
  • Initializes our View holder.
  • Binds data to our views.
package com.tutorials.hp.recyclerviewarray;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

    Context c;
    String[] spacecrafts;

    public MyAdapter(Context c, String[] spacecrafts) {
        this.c = c;
        this.spacecrafts = spacecrafts;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(c).inflate(R.layout.model, parent, false);
        return new MyViewHolder(v);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {

        //BIND DATA
        holder.nameTxt.setText(spacecrafts[position]);

    }

    @Override
    public int getItemCount() {
        return spacecrafts.length;
    }
}
(c) .Our MainActivity
  • Launcher activity.
  • References RecyclerView and sets its layout manager.
  • Instantiates and sets our adapter to RecyclerView.
package com.tutorials.hp.recyclerviewarray;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

public class MainActivity extends AppCompatActivity {

    RecyclerView rv;
    String[] spacecrafts={"Juno","Hubble","Casini","WMAP","Spitzer","Pioneer","Columbia","Challenger","Apollo","Curiosity"};

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

        rv = (RecyclerView) findViewById(R.id.rv);
        rv.setLayoutManager(new LinearLayoutManager(this));

        //ADAPTER
        MyAdapter adapter = new MyAdapter(this, spacecrafts);
        rv.setAdapter(adapter);
    }
}
(d). Our Model XML Layout
  • A single cardview in our recyclerview.
  • Shall be inflated to a view item.
<?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="5dp"
    card_view_cardElevation="5dp"
    android_layout_height="200dp">

            <TextView
                android_layout_width="match_parent"
                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_textStyle="bold"
                android_layout_alignParentLeft="true"
                />

</android.support.v7.widget.CardView>

2. Android RecyclerView – Fill With ArrayList

[center] How to populate a recyclerview from an arraylist. [/center]

This is a simple RecyclerView and ArrayList tutorial.Here is what we do:

  • Fill RecyclerView with data from a simple ArrayList.
  • We derive from RecycelView.ViewHolder to get our custom viewholder class.
  • We aslo derive from RecyclerView.Adapter to get our adapter class that helps us bind our data to our RecyclerView.
  • We create a model layout using cardview that’s inflated to a view item for our recyclerview.
What This Example Teaches
  1. How to fill a recyclerview with an arraylist.
  2. How to show cardviews in a recyclerview.
  3. How to inflate a model layout into an java view item.
(a). Our View Holder Class
  • Holds our views for recycling.
package com.tutorials.hp.recyclerviewlist;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

public class MyViewHolder extends RecyclerView.ViewHolder {

    TextView nameTxt;

    public MyViewHolder(View itemView) {
        super(itemView);

        nameTxt = (TextView) itemView.findViewById(R.id.nameTxt);

    }

}
(b). Our Adapter Class
  • Responisble for layout inflation.
  • Initializes our View holder.
  • Binds data to our views.
package com.tutorials.hp.recyclerviewlist;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;

public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

    Context c;
    ArrayList<String> numbers;

    public MyAdapter(Context c, ArrayList<String> numbers) {
        this.c = c;
        this.numbers = numbers;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(c).inflate(R.layout.model, parent, false);
        return new MyViewHolder(v);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {

        //BIND DATA
        holder.nameTxt.setText(numbers.get(position));

    }

    @Override
    public int getItemCount() {
        return numbers.size();
    }
}
(c). Our MainActivity
  • Launcher activity.
  • References RecyclerView and sets its layout manager.
  • Instantiates and sets our adapter to RecyclerView.
package com.tutorials.hp.recyclerviewlist;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ArrayList<String> numbers=new ArrayList<>();

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

        //SETUP RECYCLER
        RecyclerView rv= (RecyclerView) findViewById(R.id.rv);
        rv.setLayoutManager(new LinearLayoutManager(this));

        //FILL LIST
        fillList();

        //adapter
        MyAdapter adapter=new MyAdapter(this,numbers);
        rv.setAdapter(adapter);

    }

    private void fillList()
    {
        for(int i=0;i<10;i++)
        {
            numbers.add("Number "+String.valueOf(i));
        }

    }
}
(d). Our Model XML Layout
  • A single cardview in our recyclerview.
  • Shall be inflated to a view item.
<?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="5dp"
    card_view_cardElevation="5dp"
    android_layout_height="200dp">

            <TextView
                android_layout_width="match_parent"
                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_textStyle="bold"
                android_layout_alignParentLeft="true"
                />

</android.support.v7.widget.CardView>

3. Android RecyclerView – Fill With List Of Objects

In this tutorial we take a look at how to populate a recyclerView with list of objects.Our recycerview is going to consist of two textviews inside a cardview.

(a). Our build.gradle
  •  Lets add two dependencies,support design and cardview in our buil.gradle(Module:app)
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.0.0'
    compile 'com.android.support:design:24.0.0'
    compile 'com.android.support:cardview-v7:24.0.0'
}
(b). Our Model Class
  • Is our data object representing a single Person object.
package com.tutorials.hp.recyclerviewandobjects;

public class Person {

    int id;
    String name,country;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }
}
(c). Our MainActivity
  • Our launcher activity
  • We set our layoutmanager as well as our adapter instance to our RecyclerView.
  • We fill our arraylist with data.
package com.tutorials.hp.recyclerviewandobjects;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.tutorials.hp.recyclerviewandobjects.m_Recycler.MyAdapter;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ArrayList<Person> people=new ArrayList<>();

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

        //RECYCLERVIEW
        RecyclerView rv= (RecyclerView) findViewById(R.id.rv);
        rv.setLayoutManager(new LinearLayoutManager(this));

        //FILL LIST
        fillPeople();

        //ADAPTER
        MyAdapter adapter=new MyAdapter(this,people);
        rv.setAdapter(adapter);

    }

    private void fillPeople()
    {
        people.clear();

        Person p=new Person();
        p.setName("Micky");
        p.setCountry("Armenia");
        people.add(p);

        p=new Person();
        p.setName("Nemanja");
        p.setCountry("Serbia");
        people.add(p);

        p=new Person();
        p.setName("Lucy");
        p.setCountry("Russia");
        people.add(p);

        p=new Person();
        p.setName("Rebecca");
        p.setCountry("South Africa");
        people.add(p);

        p=new Person();
        p.setName("Singh");
        p.setCountry("India");
        people.add(p);

        p=new Person();
        p.setName("Kurt");
        p.setCountry("France");
        people.add(p);

        p=new Person();
        p.setName("Vicente");
        p.setCountry("Spain");
        people.add(p);
    }
}
(d). Our ViewHolder class
  • Holds our textviews for recycling.
package com.tutorials.hp.recyclerviewandobjects.m_Recycler;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.tutorials.hp.recyclerviewandobjects.R;

public class MyViewHolder extends RecyclerView.ViewHolder {

    TextView nameTxt,countryTxt;

    public MyViewHolder(View itemView) {
        super(itemView);

        nameTxt= (TextView) itemView.findViewById(R.id.nameTxt);
        countryTxt= (TextView) itemView.findViewById(R.id.countryTxt);

    }

}
(e). Our Adapter class
  • Responsible for layout inflation.
  • Also binding data to our views
package com.tutorials.hp.recyclerviewandobjects.m_Recycler;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.tutorials.hp.recyclerviewandobjects.Person;
import com.tutorials.hp.recyclerviewandobjects.R;

import java.util.ArrayList;

public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

    Context c;
    ArrayList<Person> people;

    public MyAdapter(Context c, ArrayList<Person> people) {
        this.c = c;
        this.people = people;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v= LayoutInflater.from(c).inflate(R.layout.model,parent,false);
        return new MyViewHolder(v);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {

        //BIND DATA
        holder.nameTxt.setText(people.get(position).getName());
        holder.countryTxt.setText(people.get(position).getCountry());

    }

    @Override
    public int getItemCount() {
        return people.size();
    }
}
(f). Model.xml
<?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="5dp"
    card_view_cardElevation="5dp"
    android_layout_height="200dp">

<LinearLayout
    android_orientation="vertical"
    android_layout_width="match_parent"
    android_layout_height="wrap_content">
    <TextView
        android_layout_width="match_parent"
        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_textStyle="bold"
        android_layout_alignParentLeft="true"
        />
    <TextView
        android_layout_width="match_parent"
        android_layout_height="wrap_content"
        android_textAppearance="?android:attr/textAppearanceLarge"
        android_text="Country"
        android_id="@+id/countryTxt"
        android_padding="10dp"
        android_textColor="@color/colorPrimary"
        android_textStyle="bold"
        android_layout_alignParentLeft="true"
        />
</LinearLayout>
</android.support.v7.widget.CardView>
(g). Download

GitHub : Source

4. Android RecyclerView CardView and OnItemClick

Hello android recyclerview onItemClick here, this is what we cover :

  1. LinearLayout RecyclerView with cardview view items.
  2. ViewHolder to hold our views.
  3. Adapter where we inflate our layouts and bind data to views.
  4. Handle ItemClicks for our RecyclerView,in which case we show a simple Toast message.
(a). Our MainActivity.
  • Launcher activity.
  • Setup RecyclerView with its LayoutManager and adapter
  • Get data
package com.tutorials.hp.simplerecyclerview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.tutorials.hp.simplerecyclerview.m_Recycler.MyAdapter;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

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

        //SET UP RECYCLERVIEW
        RecyclerView rv= (RecyclerView) findViewById(R.id.rv);
        rv.setLayoutManager(new LinearLayoutManager(this));

        //ADAPTER
        MyAdapter adapter=new MyAdapter(this,getData());
        rv.setAdapter(adapter);

    }

    //FILL DATA
    private ArrayList<String> getData()
    {
        ArrayList<String> languages=new ArrayList<>();
        languages.clear();

        //FILL
        languages.add("Java");
        languages.add("C#");
        languages.add("VB.NET");
        languages.add("PHP");
        languages.add("Python");
        languages.add("Ruby");
        languages.add("C");
        languages.add("C++");
        languages.add("Fortran");
        languages.add("Cobol");
        languages.add("Perl");
        languages.add("Prolog");

        return languages;
    }
}
(b). Our ViewHolder class.
  • Holds our views for recycling
  • Listen for View onClick events.
package com.tutorials.hp.simplerecyclerview.m_Recycler;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.tutorials.hp.simplerecyclerview.R;

public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    TextView nameTxt;
    ItemClickListener itemClickListener;

    public MyViewHolder(View itemView) {
        super(itemView);

        nameTxt= (TextView) itemView.findViewById(R.id.nameTxt);

        itemView.setOnClickListener(this);
    }

    public void setItemClickListener(ItemClickListener itemClickListener)
    {
        this.itemClickListener=itemClickListener;
    }

    @Override
    public void onClick(View view) {
        this.itemClickListener.onItemClick(this.getLayoutPosition());
    }
}
(c). Our Adapter class.
  • We inflate our layout
  • Then bind data to views.
package com.tutorials.hp.simplerecyclerview.m_Recycler;

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

import com.tutorials.hp.simplerecyclerview.R;

import java.util.ArrayList;

public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

    Context c;
    ArrayList<String> languages;

    public MyAdapter(Context c, ArrayList<String> languages) {
        this.c = c;
        this.languages = languages;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v= LayoutInflater.from(c).inflate(R.layout.model,parent,false);
        return new MyViewHolder(v);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {

        //BIND DATA
        holder.nameTxt.setText(languages.get(position));

        //ITEM CLICK
        holder.setItemClickListener(new ItemClickListener() {
            @Override
            public void onItemClick(int pos) {
                Toast.makeText(c, languages.get(pos), Toast.LENGTH_SHORT).show();
            }
        });

    }

    @Override
    public int getItemCount() {
        return languages.size();
    }
}
(d). Our ItemClickListener Interface.
package com.tutorials.hp.simplerecyclerview.m_Recycler;

public interface ItemClickListener {

    void onItemClick(int pos);

}
(e). Model.xml
  • Our model layout.
<?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="5dp"
    card_view_cardElevation="5dp"
    android_layout_height="200dp">
            <TextView
                android_layout_width="match_parent"
                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_textStyle="bold"
                android_layout_alignParentLeft="true"
                />
</android.support.v7.widget.CardView>
Download

Download code below:

GitHub : Source

 

Share
Adv

3 Examples

  1. Android RecyclerView – StaggeredGrid With Images and Text

    This is an android recyclerview staggered grid example with images and text.

    RecyclerView normally is quite flexible when it comes to how it positions views it is rendering.

    There are three in-built layouts it uses to position data:

    1. LinearLayout.
    2. GridLayout.
    3. StaggeredGridLayout.

    Let’s see how to use the StaggeredGridLayout.

     

    1. Create Basic Activity Project

    1. First create an empty project in android studio. Go to File –> New Project.
    2. Type the application name and choose the company name.
    3. Choose minimum SDK.
    4. Choose Basic activity.
    5. Click Finish.

    Basic activity will have a toolbar and floating action button already added in the layout

    Normally two layouts get generated with this option:

    No. Name Type Description
    1. activity_main.xml XML Layout Will get inflated into MainActivity Layout.Typically contains appbarlayout with toolbar.Also has a floatingactionbutton.
    2. content_main.xml XML Layout Will be included into activity_main.xml.You add your views and widgets here.
    3. MainActivity.java Class Main Activity.

    In this example I used a basic activity.

    The activity will automatically be registered in the android_manifest.xml. Android Activities are components and normally need to be registered as an application component.

    If you’ve created yours manually then register it inside the <application>...<application> as following, replacing the MainActivity with your activity name:

            <activity android_name=".MainActivity">
    
                <intent-filter>
    
                    <action android_name="android.intent.action.MAIN" />
    
                    <category android_name="android.intent.category.LAUNCHER" />
    
                </intent-filter>
    
            </activity>

    You can see that one action and category are specified as intent filters. The category makes our MainActivity as launcher activity. Launcher activities get executed first when th android app is run.

    Advantage of Creating Basic Activity project

    You can optionally choose empty activity over basic activity for this project.

    However basic activity has the following advantages:

    No. Advantage
    1. Provides us a readymade toolbar which gives us actionbar features yet easily customizable
    2. Provides us with appbar layout which implements material design appbar concepts.
    3. Provides a FloatinActionButton which we can readily use to initiate quick actions especially in examples like these.
    4. Decouples our custom content views and widgets from the templating features like toolbar.

    Generated Project Structure

    AndroidStudio will generate for you a project with default configurations via a set of files and directories.

    Here are the most important of them:

    No. File Major Responsibility
    1. build/ A directory containing resources that have been compiled from the building of application and the classes generated by android tools. Such a tool is the R.java file. R.java file normally holds the references to application resources.
    2. libs/ To hold libraries we use in our project.
    3. src/main/ To hold the source code of our application.This is the main folder you work with.
    4. src/main/java/ Contains our java classes organized as packages.
    5. src/main/res/ Contains our project resources folders as follows.
    6. src/main/res/drawable/ Contains our drawable resources.
    7. src/main/res/layout/ Contains our layout resources.
    8. src/main/res/menu/ Contains our menu resources XML code.
    9. src/main/res/values/ Contains our values resources XML code.These define sets of name-value pairs and can be strings, styles and colors.
    10. AndroidManifest.xml This file gets autogenerated when we create an android project.It will define basic information needed by the android system like application name,package name,permissions,activities,intents etc.
    11. build.gradle Gradle Script used to build the android app.

    2. Add Dependencies

    Add dependencies in your build.gradle:

    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'
    }

    3. Create User Interface

    User interfaces are typically created in android using XML layouts as opposed by direct java coding.

    This is an example fo declarative programming.

    ######### Advantages of Using XML over Java

    No. Advantage
    1. Declarative creation of widgets and views allows us to use a declarative language XML which makes is easier.
    2. It’s easily maintanable as the user interface is decoupled from your Java logic.
    3. It’s easier to share or download code and safely test them before runtime.
    4. You can use XML generated tools to generate XML

    Here are our layouts for this project:
    (a). activity_main.xml

    • This layout gets inflated to MainActivity user interface.
    • It includes the content_main.xml.

    Here are some of the widgets, views and viewgroups that get employed”

    No. View/ViewGroup Package Role
    1. CordinatorLayout android.support.design.widget Super-powered framelayout that provides our application’s top level decoration and is also specifies interactions and behavioros of all it’s children.
    2. AppBarLayout android.support.design.widget A LinearLayout child that arranges its children vertically and provides material design app bar concepts like scrolling gestures.
    3. ToolBar <android.support.v7.widget A ViewGroup that can provide actionbar features yet still be used within application layouts.
    4. FloatingActionButton android.support.design.widget An circular imageview floating above the UI that we can use as buttons.
    <?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.staggeredgridrecycler.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 layout gets included in your activity_main.xml.
    Add a RecyclerView here.

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

    RecyclerView Staggered Grid model.

    <?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="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_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's 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" />
    
        </RelativeLayout>
    </android.support.v7.widget.CardView>

    4. Java Classes

    (a). TVShow.java

    Our data object.

    package com.tutorials.hp.staggeredgridrecycler;
    
    public class TVShow {
    
        private String name,description;
        private int image;
    
        public TVShow(String name, String description, int image) {
            this.name = name;
            this.description = description;
            this.image = image;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getDescription() {
            return description;
        }
    
        public void setDescription(String description) {
            this.description = description;
        }
    
        public int getImage() {
            return image;
        }
    
        public void setImage(int image) {
            this.image = image;
        }
    }
    (b). ItemClickListener.java

    Our ItenClick listener interface.

    package com.tutorials.hp.staggeredgridrecycler;
    
    import android.view.View;
    
    public interface ItemClickListener {
    
        void onItemClick(View v,int pos);
    }
    (c). MyHolder.java

    Our RecyclerView.ViewHolder class.

    package com.tutorials.hp.staggeredgridrecycler;
    
    import android.support.v7.widget.RecyclerView;
    import android.view.View;
    import android.widget.ImageView;
    import android.widget.TextView;
    
    public class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    
        ImageView img;
        TextView nameTxt,desc;
        ItemClickListener itemClickListener;
    
        public MyHolder(View itemView) {
            super(itemView);
    
            nameTxt= (TextView) itemView.findViewById(R.id.nameTxt);
            desc= (TextView) itemView.findViewById(R.id.descTxt);
            img= (ImageView) itemView.findViewById(R.id.movieImage);
    
            itemView.setOnClickListener(this);
        }
    
        public void setItemClickListener(ItemClickListener ic)
        {
            this.itemClickListener=ic;
        }
    
        @Override
        public void onClick(View v) {
            this.itemClickListener.onItemClick(v,getLayoutPosition());
        }
    }
    (d). MyAdapter.java

    Our RecyclerView.Adapter class.

    package com.tutorials.hp.staggeredgridrecycler;
    
    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;
    
    import java.util.ArrayList;
    
    public class MyAdpter extends RecyclerView.Adapter<MyHolder> {
    
        Context c;
        ArrayList<TVShow> tvShows;
    
        public MyAdpter(Context c, ArrayList<TVShow> tvShows) {
            this.c = c;
            this.tvShows = tvShows;
        }
    
        //INITIALIZING OUR HOLDER
        @Override
        public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.model,null);
            MyHolder holder=new MyHolder(v);
            return holder;
        }
    
        //BIND DATA TO VIEWS
        @Override
        public void onBindViewHolder(MyHolder holder, int position) {
            holder.nameTxt.setText(tvShows.get(position).getName());
            holder.desc.setText(tvShows.get(position).getDescription());
            holder.img.setImageResource(tvShows.get(position).getImage());
    
            holder.setItemClickListener(new ItemClickListener() {
                @Override
                public void onItemClick(View v, int pos) {
                    Snackbar.make(v,tvShows.get(pos).getName(),Snackbar.LENGTH_SHORT).show();
                }
            });
    
        }
    
        //TOTAL NUM OF MOVIES
        @Override
        public int getItemCount() {
            return tvShows.size();
        }
    }
    (e). MainActivity.java

    Our Main Activity.

    package com.tutorials.hp.staggeredgridrecycler;
    
    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.RecyclerView;
    import android.support.v7.widget.StaggeredGridLayoutManager;
    import android.support.v7.widget.Toolbar;
    import android.view.View;
    import android.view.Menu;
    import android.view.MenuItem;
    
    import java.util.ArrayList;
    
    public class MainActivity extends AppCompatActivity {
    
        RecyclerView rv;
        MyAdpter 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();
                }
            });
    
            rv= (RecyclerView) findViewById(R.id.myRecycler);
    
            //SET LAYOUT
            rv.setLayoutManager(new StaggeredGridLayoutManager(2,1));
            rv.setItemAnimator(new DefaultItemAnimator());
    
            //ADAPTER
            adapter=new MyAdpter(this,getTVShows());
            rv.setAdapter(adapter);
    
        }
        private ArrayList<TVShow> getTVShows() {
            ArrayList<TVShow> tvShows=new ArrayList<>();
            String desc=" John Doe a former FBI Agent and now Physics teacher .is wrongly accussed of murdering an innocent child.....";
            TVShow tv=new TVShow("BLACKLIST",desc,R.drawable.blacklist);
            tvShows.add(tv);
    
            desc=" Jack Gruller 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.After having eveaded the officers for more than a decade,he finds himself again in trouble.He has to do everthing to confirm himesl as clean. He's convinces hacker Aram to join him.....";
            tv=new TVShow("Breaking Bad",desc,R.drawable.breaking);
            tvShows.add(tv);
    
            desc=" Joe Spike 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's convinces hacker Aram to join him.....";
            tv=new TVShow("Ghost Rider",desc,R.drawable.ghost);
            tvShows.add(tv);
    
            desc=" John Mo 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's convinces hacker Aram to join him.....";
            tv=new TVShow("Game Of Thrones",desc,R.drawable.thrones);
            tvShows.add(tv);
    
            desc=" Curt Foe 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's convinces hacker Aram to join him.....";
            tv=new TVShow("Men In Black",desc,R.drawable.meninblack);
            tvShows.add(tv);
    
            return tvShows;
        }
    }
  2. Adv
  3. 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.

  4. Adv
  5. Android Master Detail RecyclerView Images Text

    Android Master Detail Example with RecyclerView.The RecyclerView shall comprise CardViews with images and text.We work with two activities.

    Intro

    • We are going to have two views or activities,the Master View and the Detail View.
    • The Master View shall be the Master Activity.
    • It shall be responsible for displaying a List of data.
    • The component of choice is recyclerView.
    • The data shall be images and text.
    • When clicked,we open the Detail Activity and pass the data via intents.
    • We display those data in the detail activity.
    • We have a video tutorial for this example below.You can also view the demo over there.
    • We’ve used Android Studio as our IDE.
    • The full source code is above for download.The instructions for importing to your android studio is below.

    Tools Used

    • IDE : Android Studio
    • OS : Windows 8

    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.

    The full source code reference is available above for download.If you prefer a step by step tutorial then watch our video tutorial at the bottom of this page.

    RecyclerView Master View

    Let’s go

    1. Build.Gradle(App)

    • First here’s our dependencies closure in our app level build.gradle :
    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        testCompile 'junit:junit:4.12'
        compile 'com.android.support:appcompat-v7:23.3.0'
        compile 'com.android.support:design:23.3.0'
        compile 'com.android.support:cardview-v7:23.3.0'
    
    }

    2. DetailActivity

    • Then here’s our detail activity.It shall receive data passed via intent object.
    • It shall then display that data :
    package com.tutorials.hp.masterdetailrecyclerview.mDetail;
    
    import android.content.Intent;
    import android.media.Image;
    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.Toolbar;
    import android.view.View;
    import android.widget.ImageView;
    import android.widget.TextView;
    
    import com.tutorials.hp.masterdetailrecyclerview.R;
    
    public class DetailActivity extends AppCompatActivity {
    
        TextView nameTxt;
        ImageView img;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_detail);
            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();
                }
            });
    
            //INITIALIZE VIEWS
            nameTxt= (TextView) findViewById(R.id.nameTxtDetail);
            img= (ImageView) findViewById(R.id.spacecraftImageDetail);
    
            //RECEIVE DATA
            Intent i=this.getIntent();
            String name=i.getExtras().getString("NAME_KEY");
            int image=i.getExtras().getInt("IMAGE_KEY");
    
            //BIND DATA
            nameTxt.setText(name);
            img.setImageResource(image);
        }
    
    }

    3. RecyclerView Adapter

    • We are suing recyclerView as our component of choice,here’s our RecyclerView adapter.
    • It derives from RecyclerView.Adapter.
    • We pass it a Context and ArrayList as our parameters.
    • We override three methods : onCreateViewHolder,onBindViewHolder and getItemCount.
    package com.tutorials.hp.masterdetailrecyclerview.mRecycler;
    
    import android.content.Context;
    import android.content.Intent;
    import android.support.v7.widget.RecyclerView;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Toast;
    
    import com.tutorials.hp.masterdetailrecyclerview.R;
    import com.tutorials.hp.masterdetailrecyclerview.mData.SpaceCraft;
    import com.tutorials.hp.masterdetailrecyclerview.mDetail.DetailActivity;
    
    import java.util.ArrayList;
    
    public class MyAdapter extends RecyclerView.Adapter<MyHolder> {
    
        Context c;
        ArrayList<SpaceCraft> spaceCrafts;
    
        public MyAdapter(Context c, ArrayList<SpaceCraft> spaceCrafts) {
            this.c = c;
            this.spaceCrafts = spaceCrafts;
        }
    
        @Override
        public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.model,parent,false);
            return new MyHolder(v);
        }
    
        @Override
        public void onBindViewHolder(MyHolder holder, int position) {
            final String name=spaceCrafts.get(position).getName();
            final int image=spaceCrafts.get(position).getImage();
    
            //BIND DATA
            holder.nameTxt.setText(name);
            holder.img.setImageResource(image);
    
            holder.setItemClickListener(new ItemClickListener() {
                @Override
                public void onItemClick(int pos) {
                    openDetailActivity(name,image);
                    Toast.makeText(c,name,Toast.LENGTH_SHORT).show();
                }
            });
    
        }
    
        @Override
        public int getItemCount() {
            return spaceCrafts.size();
        }
    
        private void openDetailActivity(String name,int image)
        {
            Intent i=new Intent(c, DetailActivity.class);
    
            //PACK DATA TO SEND
            i.putExtra("NAME_KEY",name);
            i.putExtra("IMAGE_KEY",image);
    
            //open activity
            c.startActivity(i);
    
        }
    }

    4. MainActivity

    • Here’s our MainActivity class,our launcher activity in this case.
    • We reference our RecyclerView by its id from our xml layout.
    • We instantiate our adapter.
    • We set the layoutmanager to the recyclerview and set its adapter.
    package com.tutorials.hp.masterdetailrecyclerview;
    
    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.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;
    
    import com.tutorials.hp.masterdetailrecyclerview.mData.SpaceCraftsCollection;
    import com.tutorials.hp.masterdetailrecyclerview.mRecycler.MyAdapter;
    
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
    
            RecyclerView rv= (RecyclerView) findViewById(R.id.rv);
            rv.setLayoutManager(new LinearLayoutManager(this));
    
            MyAdapter adapter=new MyAdapter(this, SpaceCraftsCollection.getSpaceCrafts());
            rv.setAdapter(adapter);
        }
    
    }

    How To Run

    1. Download the project.
    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 Resources

    Resource Link
    GitHub Browse Browse
    GitHub Download Link Download

    Good day.




Share an Example

Share an Example

Browse
What is the capital of Egypt? ( Cairo )