Android Working with Recyclerview

While ListView was much appreciated by the developers, RecyclerView has impressed them more with its advanced features and improved performance. Developers can create both grids and lists without any hassle using CardView and RecyclerView together. To understand RecyclerView better, we need to go through some examples and a detailed tutorial. In this particular tutorial, we will learn how to use RecyclerView with a custom layout. The tutorial will also include writing an adapter class, adding list divider and row click listener. Out final product will be a Recyclerview that has a list of movies along with a few more details including title, genre and year of release.

Suitable recyclerview widget with key attributes:

<android.support.v7.widget.RecyclerView

        android:id="@+id/recycler_view"

        android:scrollbars="vertical"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"/>

For this, you will need the latest version of Android Studio.

New Project Creation:

Step 1:

Switch open your Android Studio, go to File and then New Project. You must fill all the required fields with genuine information. It will now show you a pop-up asking to fill the default activity, choose Blank Activity. Proceed to the next step.

Step 2:

Log in to build.gradle and add a RecyclerView dependency. You need to rebuild the project after adding com.android.support:recyclerview-v7:26.1.0

Build.gradle

apply plugin: 'com.android.application'

android {

    compileSdkVersion 26

    buildToolsVersion '26.0.2'

    // ..

}

dependencies {

    implementationfileTree(dir: 'libs', include: ['*.jar'])

    //..

    // RecyclerView

    implementation 'com.android.support:recyclerview-v7:26.1.0'

}

Step 3:

The Android Studio willnow create two layout file for each activity making best use of the latest tools. It created two layout for main activity- activity_main.xml (contains CoordinatorLayout and AppBarLayout) and content_main.xml (for the actual content).

Open the content_main.xml and the recycler view widget.

content_main.xml

<?xmlversion="1.0"encoding="utf-8"?>

<RelativeLayout

    xmlns:android="

http://schemas.android.com/apk/res/android

"

    xmlns:tools="

http://schemas.android.com/tools

"

    xmlns:app="

http://schemas.android.com/apk/res-auto

"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    app:layout_behavior="@string/appbar_scrolling_view_behavior"

    tools:showIn="@layout/activity_main"

    tools:context=".MainActivity">

    <android.support.v7.widget.RecyclerView

        android:id="@+id/recycler_view"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:scrollbars="vertical"/>

</RelativeLayout>

Step 4:

Now add colors by opening colors.xml which can be find under res-values

colors.xml


<?xmlversion="1.0"encoding="utf-8"?>

<resources>

    <colorname="colorPrimary">#3F51B5</color>

    <colorname="colorPrimaryDark">#303F9F</color>

    <colorname="colorAccent">#FF4081</color>

    <colorname="year">#999999</color>

    <colorname="title">#222222</color>

</resources>

Step 5:

Now open the dimes.xml, for adding the dimensions. It can also be found under res-value.

dimens.xml


<resources>

    <!-- Default screen margins, per the Android Design guidelines. -->

    <dimenname="activity_horizontal_margin">16dp</dimen>

    <dimenname="activity_vertical_margin">16dp</dimen>

    <dimenname="fab_margin">16dp</dimen>

    <dimenname="row_padding_vertical">10dp</dimen>

</resources>

Adapter Class Writing:

You have now successfully added the RecyclerView widget. To render the data, you need to write the adapter class. Adapter Class is same for Recycler View and ListView, however, each is

Step 6:

You need to create a new class titled Movie.java and further declare title, genre, and the year. It is important to add the getter/setter methods for each one of the variable.

Movie.java

packageinfo.androidhive.recyclerview;

publicclassMovie {

    privateString title, genre, year;

    publicMovie() {

    }

    publicMovie(String title, String genre, String year) {

        this.title = title;

        this.genre = genre;

        this.year = year;

    }

    publicString getTitle() {

        returntitle;

    }

    publicvoidsetTitle(String name) {

        this.title = name;

    }

    publicString getYear() {

        returnyear;

    }

    publicvoidsetYear(String year) {

        this.year = year;

    }

    publicString getGenre() {

        returngenre;

    }

    publicvoidsetGenre(String genre) {

        this.genre = genre;

    }

}

Step 7:

Using the below code, you need to create a new layout with name movie_list_row.xml. It will enable a single row in the recycler view that will display name, genre and year of release.

movie_list_row.xml

<?xmlversion="1.0"encoding="utf-8"?>

<RelativeLayoutxmlns:android="

http://schemas.android.com/apk/res/android

"

    android:layout_width="match_parent"

    android:layout_height="wrap_content"

    android:background="?android:attr/selectableItemBackground"

    android:clickable="true"

    android:focusable="true"

    android:orientation="vertical"

    android:paddingBottom="@dimen/row_padding_vertical"

    android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/row_padding_vertical">

    <TextView

        android:id="@+id/title"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_alignParentTop="true"

        android:textColor="@color/title"

        android:textSize="16dp"

        android:textStyle="bold"/>

    <TextView

        android:id="@+id/genre"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_below="@id/title"/>

    <TextView

        android:id="@+id/year"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignParentRight="true"

        android:textColor="@color/year"/>

</RelativeLayout>

Step 8:

Create a new class with name MoviesAdapter.java and then add the below mentioned code. The onCreateViewHolder() method here will inflate movie_list_row.xml. The onCreateViewHolder() method enables you to fill the appropriate data for each row.

MoviesAdapter.java

packageinfo.androidhive.recyclerview;

importandroid.support.v7.widget.RecyclerView;

importandroid.view.LayoutInflater;

importandroid.view.View;

importandroid.view.ViewGroup;

importandroid.widget.TextView;

importjava.util.List;

publicclassMoviesAdapter extendsRecyclerView.Adapter<MoviesAdapter.MyViewHolder> {

    privateList<Movie>moviesList;

    publicclassMyViewHolder extendsRecyclerView.ViewHolder {

        publicTextView title, year, genre;

        publicMyViewHolder(View view) {

            super(view);

            title = (TextView) view.findViewById(R.id.title);

            genre = (TextView) view.findViewById(R.id.genre);

            year = (TextView) view.findViewById(R.id.year);

        }

    }

    publicMoviesAdapter(List<Movie>moviesList) {

        this.moviesList = moviesList;

    }

    @Override

    publicMyViewHolderonCreateViewHolder(ViewGroup parent, intviewType) {

        View itemView = LayoutInflater.from(parent.getContext())

                .inflate(R.layout.movie_list_row, parent, false);

        returnnewMyViewHolder(itemView);

    }

    @Override

    publicvoidonBindViewHolder(MyViewHolder holder, intposition) {

        Movie movie = moviesList.get(position);

        holder.title.setText(movie.getTitle());

        holder.genre.setText(movie.getGenre());

        holder.year.setText(movie.getYear());

    }

    @Override

    publicintgetItemCount() {

        returnmoviesList.size();

    }

}

Step 9:

You must now access the MainActivity.java and make the below mentioned changes. The prepareMovieData() method used below adds data to each category of the list view.

MainActivity.java

packageinfo.androidhive.recyclerview;

importandroid.content.Context;

importandroid.os.Bundle;

importandroid.support.v7.app.AppCompatActivity;

importandroid.support.v7.widget.DefaultItemAnimator;

importandroid.support.v7.widget.LinearLayoutManager;

importandroid.support.v7.widget.RecyclerView;

importandroid.support.v7.widget.Toolbar;

importandroid.view.GestureDetector;

importandroid.view.MotionEvent;

importandroid.view.View;

importandroid.widget.Toast;

importjava.util.ArrayList;

importjava.util.List;

publicclassMainActivity extendsAppCompatActivity {

    privateList<Movie>movieList = newArrayList<>();

    privateRecyclerViewrecyclerView;

    privateMoviesAdaptermAdapter;

    @Override

    protectedvoidonCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);

        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

        mAdapter = newMoviesAdapter(movieList);

        RecyclerView.LayoutManagermLayoutManager = newLinearLayoutManager(getApplicationContext());

        recyclerView.setLayoutManager(mLayoutManager);

        recyclerView.setItemAnimator(newDefaultItemAnimator());

        recyclerView.setAdapter(mAdapter);

        prepareMovieData();

    }

    privatevoidprepareMovieData() {

        Movie movie = newMovie("Mad Max: Fury Road", "Action & Adventure", "2015");

        movieList.add(movie);

        movie = newMovie("Inside Out", "Animation, Kids & Family", "2015");

        movieList.add(movie);

        movie = newMovie("Star Wars: Episode VII - The Force Awakens", "Action", "2015");

        movieList.add(movie);

        movie = newMovie("Shaun the Sheep", "Animation", "2015");

        movieList.add(movie);

        movie = newMovie("The Martian", "Science Fiction & Fantasy", "2015");

        movieList.add(movie);

        movie = newMovie("Mission: Impossible Rogue Nation", "Action", "2015");

        movieList.add(movie);

        movie = newMovie("Up", "Animation", "2009");

        movieList.add(movie);

        movie = newMovie("Star Trek", "Science Fiction", "2009");

        movieList.add(movie);

        movie = newMovie("The LEGO Movie", "Animation", "2014");

        movieList.add(movie);

        movie = newMovie("Iron Man", "Action & Adventure", "2008");

        movieList.add(movie);

        movie = newMovie("Aliens", "Science Fiction", "1986");

        movieList.add(movie);

        movie = newMovie("Chicken Run", "Animation", "2000");

        movieList.add(movie);

        movie = newMovie("Back to the Future", "Science Fiction", "1985");

        movieList.add(movie);

        movie = newMovie("Raiders of the Lost Ark", "Action & Adventure", "1981");

        movieList.add(movie);

        movie = newMovie("Goldfinger", "Action & Adventure", "1965");

        movieList.add(movie);

        movie = newMovie("Guardians of the Galaxy", "Science Fiction & Fantasy", "2014");

        movieList.add(movie);

        mAdapter.notifyDataSetChanged();

    }

}

Now when you will run the app, you can easily find the movies listed with appropriate details.

Leave a Reply

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