Android RecyclerView

Android RecyclerView

Android RecyclerView Example – In this tutorial you will learn following terms it will take too much time this chapter is long so be patient and love to read,think and code!

android recyclerview

  • 1. What is Android RecyclerView?
  • 2. Android RecyclerView Example
    • 2.1. Creating Android Project
    • 2.2. Declaring Android Activity Layout
    • 2.3. Android RecyclerView Row Layout
    • 2.4. Creating RecyclerView Adapter
    • 2.5. Activity Using RecyclerView
  • 3. Handle RecyclerView Click Event

So we starts from zero.

What Is Android RecyclerView?

In Google android 5.0 Lollipop, Android os unveiled android RecyclerView widget. Android RecyclerView is adaptable and effective version of ListView. It really is an pot for rendering much larger data group of views that may be recycled and scrolled very successfully. Android RecyclerView is similar to traditional ListView widget, but with an increase of overall flexibility to customizes and optimized to utilize greater datasets. It runs on the subclass of RecyclerView.Adapter for providing views that symbolize items in a data set in place.

Android os SDK doesn’t includes the RecyclerView class. You need to include the next support collection graddle dependency to task build.graddle file.

compile 'com.android.support:recyclerview-v7:24.0.0'

 

This guide clarifies how to use and personalize Android RecyclerView in Android os applications.

Android RecyclerView Example

Throughout this android recyclerview example we will download the info from JSON API, parse and screen the things on RecyclerView. As possible notice in the next image, we are using both RecyclerView and CardView for creating the app ui

Following steps must complete the android recyclerview example:

  1. Create a fresh Android Request and add the mandatory graddle dependencies
  2. Structure activity and add RecyclerView and ProgressBar
  3. Layout the RecyclerView row  item using CardView widget
  4. Develop a Custom Adapter for RecyclerView
  5. Create main Activity to initialize UI, make HTTP Server get and render data on RecyclerView
  6. Giving an answer to RecyclerView click event

Creating Android os Project

Let us get started with creating a fresh Android job in Android Studio. After the task is created, wide open app build.graddle file and add the next dependency libraries.

dependencies {
    compile 'com.android.support:recyclerview-v7:24.0.0'
    compile 'com.android.support:cardview-v7:24.0.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    // ...
}

 

Notice that, we’ve added RecyclerView, CardView support libraries and Picasso dependency component.

Picasso can be an Start Source image loader catalogue created and preserved by Square. It really is one of the powerful image download and caching catalogue for Android.

Adding Internet Agreement:

<uses-permission android:name="android.permission.INTERNET" />

 

Declaring Activity Layout

Why don’t we now explain the design for Activity. We will put in a RecyclerView and ProgressBar in the RelativeLayout. The improvement pub will be viewed as the data data from REST API has been downloaded.

Create a fresh document activity_main.xml inside design source folder and paste the next snippets.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#f1f1f1"
    android:padding="12dp"
    tools:context="com.androdevelopment.recyclerview.MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerInParent="true"/>

    <ProgressBar
        android:id="@+id/progress_bar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"/>

</RelativeLayout>

 Android RecyclerView Row Layout

Within the example, each row item is displayed by way of a CardView that hosts a RelativeLayout with an ImageView for the thumbnail and a TextView subject. This structure resides in the record list_row.xml.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:cardview="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="5dp"
    cardview:cardCornerRadius="2dp"
    cardview:cardElevation="3dp"
    cardview:cardUseCompatPadding="true">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/thumbnail"
            android:layout_width="match_parent"
            android:layout_height="180dp"
            android:layout_alignParentTop="true"
            android:scaleType="centerCrop"
            android:src="@drawable/placeholder"/>

        <TextView
            android:id="@+id/title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/thumbnail"
            android:layout_centerVertical="true"
            android:layout_marginLeft="12dp"
            android:maxLines="3"
            android:padding="8dp"
            android:textAppearance="@style/TextAppearance.AppCompat.Headline"
            android:textColor="#444"
            android:textSize="18dp"
            android:textStyle="bold"/>

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

 Creating Android RecyclerView Adapter

Android os RecyclerView includes special kind of adapter which works just about identical to traditional Android osadapters but with additional functionalities.It runs on the subclass of RecyclerView.Adapter for providing views that signify items in a data place.The excess functionalities of RecyclerView.Adapter are:

It offers two new methods like onCreateViewHolder() and onBindViewHolder() to arrange the code. You need to override both of these options for inflate the view and bind data to the view

Implements a ViewHolder by default. Conceptually RecyclerView.ViewHolder works identical to the ViewHolder design routine which we’ve been using with other Adapters. Manages the over head of recycling and provides better performance and scrolling

Create a fresh new class MyRecyclerViewAdapter.class and copy the next snippets.


Do You Have Any Question About This Tutorial? Ask Question Now On Andro Development & Get Answer Instantly. No Signup/Login Needed


public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.CustomViewHolder> {
    private List<FeedItem> feedItemList;
    private Context mContext;

    public MyRecyclerViewAdapter(Context context, List<FeedItem> feedItemList) {
        this.feedItemList = feedItemList;
        this.mContext = context;
    }

    @Override
    public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, null);
        CustomViewHolder viewHolder = new CustomViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(CustomViewHolder customViewHolder, int i) {
        FeedItem feedItem = feedItemList.get(i);

        //Render image using Picasso library
        if (!TextUtils.isEmpty(feedItem.getThumbnail())) {
            Picasso.with(mContext).load(feedItem.getThumbnail())
                    .error(R.drawable.placeholder)
                    .placeholder(R.drawable.placeholder)
                    .into(customViewHolder.imageView);
        }

        //Setting text view title
        customViewHolder.textView.setText(Html.fromHtml(feedItem.getTitle()));
    }

    @Override
    public int getItemCount() {
        return (null != feedItemList ? feedItemList.size() : 0);
    }

    class CustomViewHolder extends RecyclerView.ViewHolder {
        protected ImageView imageView;
        protected TextView textView;

        public CustomViewHolder(View view) {
            super(view);
            this.imageView = (ImageView) view.findViewById(R.id.thumbnail);
            this.textView = (TextView) view.findViewById(R.id.title);
        }
    }
}

 

Notice that we’ve created an private ViewHolder category. The ViewHolder class contains the mention of the each one of the ui widget on the row.the FeedItem class can be an model class that retains the parsed data retrieved from JSON API. Put in a new new data file FeedItem.java class in assembling your project source folder and add the next.

public class FeedItem {
    private String title;
    private String thumbnail;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getThumbnail() {
        return thumbnail;
    }

    public void setThumbnail(String thumbnail) {
        this.thumbnail = thumbnail;
    }
}

 Activity Using Android RecyclerView

The causing RecyclerView implementation because of this example application contains MainActivity initialization code. MainActivity creates the mRecyclerView case, download and parse the info from JSON API, instantiates the adapter and plugs in the adapter to RecyclerView.

The focus of the tutorial is small right down to RecyclerView, hence it generally does not include any reason for download and parse data from server.Once data is downloaded, inside onPostExecute() we live initializing the adapter and establishing adapter to RecyclerView case by just dialling setAdapter() method.

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "RecyclerViewExample";
    private List<FeedItem> feedsList;
    private RecyclerView mRecyclerView;
    private MyRecyclerViewAdapter adapter;
    private ProgressBar progressBar;

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

        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        progressBar = (ProgressBar) findViewById(R.id.progress_bar);

        String url = "http://androdevelopment.com/?json=get_category_posts&slug=news&count=30";
        new DownloadTask().execute(url);
    }

    public class DownloadTask extends AsyncTask<String, Void, Integer> {

        @Override
        protected void onPreExecute() {
            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        protected Integer doInBackground(String... params) {
            Integer result = 0;
            HttpURLConnection urlConnection;
            try {
                URL url = new URL(params[0]);
                urlConnection = (HttpURLConnection) url.openConnection();
                int statusCode = urlConnection.getResponseCode();

                // 200 represents HTTP OK
                if (statusCode == 200) {
                    BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = r.readLine()) != null) {
                        response.append(line);
                    }
                    parseResult(response.toString());
                    result = 1; // Successful
                } else {
                    result = 0; //"Failed to fetch data!";
                }
            } catch (Exception e) {
                Log.d(TAG, e.getLocalizedMessage());
            }
            return result; //"Failed to fetch data!";
        }

        @Override
        protected void onPostExecute(Integer result) {
            progressBar.setVisibility(View.GONE);

            if (result == 1) {
                adapter = new MyRecyclerViewAdapter(MainActivity.this, feedsList);
                mRecyclerView.setAdapter(adapter);
            } else {
                Toast.makeText(MainActivity.this, "Failed to fetch data!", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void parseResult(String result) {
        try {
            JSONObject response = new JSONObject(result);
            JSONArray posts = response.optJSONArray("posts");
            feedsList = new ArrayList<>();

            for (int i = 0; i < posts.length(); i++) {
                JSONObject post = posts.optJSONObject(i);
                FeedItem item = new FeedItem();
                item.setTitle(post.optString("title"));
                item.setThumbnail(post.optString("thumbnail"));
                feedsList.add(item);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}


 Handle of RecyclerView Click Event

Handling/Managing click event on RecyclerView is much less easy as controlling click listener in ListView or GridView. Android os RecyclerView doesn’t provide any built-in listeners or helpful way of managing click events.

why don’t we declare a app  that specifies listener’s action. When consumer clicks on the RecyclerView the listener will go back the FeedItem for the decided on row.

public interface OnItemClickListener {
    void onItemClick(FeedItem item);
}

 

Now start to adapter and declare an example variable of OnItemClickListener along with getter and setter methods.

private OnItemClickListener onItemClickListener;
public OnItemClickListener getOnItemClickListener() {
    return onItemClickListener;
}

public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
    this.onItemClickListener = onItemClickListener;
}

 

In activity class, let arranged the click listener to adapter by contacting setOnItemClickListener() method.

adapter.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(FeedItem item) {
        Toast.makeText(MainActivity.this, item.getTitle(), Toast.LENGTH_LONG).show();

    }
});

 

Now, add the View.OnClickListener to each one of the view you want to take care of click. Add the next snippet to onBindViewHolder of the RecyclerView.Adapter. When ImageView or TextView is clicked, we will have the event back again to the caller activity.

View.OnClickListener listener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        onItemClickListener.onItemClick(feedItem);
    }
};
customViewHolder.imageView.setOnClickListener(listener);
customViewHolder.textView.setOnClickListener(listener);

Here Our Tutorial Ends! 🙂

See Also:

Android ListView

Android CardView

Android RelativeLayout


Do You Have Any Question About This Tutorial? Ask Question Now On Andro Development & Get Answer Instantly. No Signup/Login Needed