651.288.7000 info@intertech.com

androidguywithrecyclerview

In case you are waking up from a Thanksgiving turkey hangover, Google heralded Android 5 – code named Lollipop – in mid-November. Along with the blog post I made this summer, you can take a look at the Android Developers Blog for a list of the big features in Android 5. This is a release that is worthy of the term “major release” and one I plan on reviewing with you over a series of blog posts in the coming months.

Ready for Material Design

Material Design is a term you are going to hear a lot about in the new Android platform. Material Design is described as “a new approach for designing apps.” Finding a clear and concise definition of Material Design can be daunting. Practically speaking, however, what Material Design brings is a new theme to be applied to apps, a new design guide which developers are encouraged to follow for UI layouts and components, widgets that can now have an elevation allowing them to cast a shadow, a new API to create custom animations such as the transition from on activity to another, and new View components for better and more flexible display of data.

RecyclerView

RecyclerView is “a more advanced and flexible version of ListView” (see here). In fact, at AnDevCon in November, I heard Chet Haase, Android UI Toolkit team lead at Google, describe RecyclerView as “ListView2.”

Benefits of Use

Why use RecyclerView? According to documentation, it scrolls more efficiently (“very efficiently”) especially when considering large data sets and data sets whose elements are changing dynamically. RecyclerView also tries to simplify data display. In my opinion, there are more helper objects or pieces to building a RecyclerView, but default implementations are in place for many of the pieces and each of these associated components are typically small and simple – making it easier to know how to address RecyclerView features you want. The RecyclerView also offers some nice visual additions like item animation that is representative of the new Material Design.

RecyclerView Tutorial

Enough talk – you are probably ready to see and experiment with a RecyclerView. This RecyclerView tutorial assumes you have Android Studio installed on your PC and that your have used the Android SDK Manager to install Lollipop (API 21). Android Studio just emerged from beta this week. It is now “the official IDE for Android development” according to the developer.android.com web site. I am seeing a rather quick shift to Android Studio on the part of most Android developers and so I am going to use Android Studio on posts about Android on this blog site going forward. You can find the Android Studio project for this post on GitHub at https://github.com/IntertechInc/android-recycler.

The RecyclerView tutorial application here simulates a stock price ticker app – showing the rise and fall of a collection of financial stocks of interest. A background service and AsynTask simulate the constant fetch of new stock prices from Wall Street (for the tutorial the prices are actually generated by random number generator). The prices are going to be displayed on a RecyclerView. The data changes rapidly and there could be a lot of data – perfect requirements for this new Lollipop widget.

Adding the Support Library

Create a new Android project that has a Blank Activity with Fragment in Android Studio. [Again, you can download the Android Studio project from bitbucket if you want to review the code without writing it yourself.]  RecyclerView is not part of the “normal” SDK. So you will need to add a support library to incorporate the RecyclerView (and its associated components) into your project. Add the RecyclerView (2nd compile line below) to your Gradle build file (build.gradle). Save the file, and clean/rebuild your project.

Fragment layout with RecyclerView

Let’s start building the app with the fragment layout that will contain the RecyclerView. We don’t have to use a fragment – especially for this simple tutorial – but ever since Android 3, its always a good practice to provide the master list widget in a fragment so that you can easily create master/detail displays. Here the RecyclerView fragment provides the master list of stocks while a future second fragment could provide the detail information of any stock selected from the master list. The idea is that master and detail may be spread over a single activity screen when on a tablet or split across two activities when on a smaller smartphone device (see this tutorial for help on the ideas of master/detail displays in Android).

masterdetail

The fragment, in this case, is comprised solely of the RecyclerView. Note the fully qualified widget reference.

RecyclerView’s Row Layout

Next, we’ll need a layout file to provide the arrangement of information in each row of the RecylcerView. The row layout will determine how each stock price will be displayed in the rows of the RecyclerView. This is not unlike how rows of a ListView had to have a layout. In this tutorial, each incoming stock price will be shown with a stock symbol, price change, timestamp of the price change and an image visually indicating whether the price change is a gain or a loss in price.

RecyclerView-Row

To this point, easy-peasy and nothing different than what you have had to do to create a ListView to display similarly.

A New Adapter

Adapters in Android provide AdapterViews (like ListView) access to data and create the correct layout for each row or item in the AdapterView. However, RecyclerView does not use the old adapter hierarchy (BaseAdapter, SimpleAdapter, SimpleCursorAdapter, ArrayAdapter, etc.). Recycler view has its own RecyclerView.Adapter that replaces the old adapter. RecyclerView.Adapter is a generic type that requires you specify its ViewHolder via type parameters. ViewHolders are discussed in the next section.

The new RecyclerView.Adapter abstract/generic class is similar in behavior to the old BaseAdapter, but it has its own unique interface. Here are the methods you need to implement:

  • getItemCount – returns the number of rows in the associated data set and the number of rows that could be displayed in the RecyclerView.
  • onCreateViewHolder – Called when the RecyclerView needs to create/add a new ViewHolder to represent a row. It creates the ViewHolder for the specified row display. Typically, this means inflating the row layout for the row and creating a ViewHolder with that layout.
  • onBindViewHolder – Called by the RecyclerView when it needs to display the data at the position/row specified as a parameter. This method updates the row’s View components with data from the dataset. Unlike the older AdapterViews (like ListView), the RecyclerView will not call this method again if the position of the item changes in the dataset unless the item itself is invalidate or a new position cannot be determined.

The RecyclerView.Adapter will need an associated data set. In this tutorial, a simple ArrayList of stock price objects is used. This list is updated by the background service and AsyncTask.

Here is the full blown RecyclerView.Adapter for the stock prices.

Note too the notifyItemInserted( ) and notifyItemRemoved( ) methods used when a new quote is added or updated. There are a number of these types of methods on this new adapter type (notifyItemMoved, notifyItemChanged, etc.) and they can all be used conveniently to update the RecyclerView through the adapter.

ViewHolder – old pattern, new implementation

The RecyclerView.ViewHolder is also a new component (that follows a pre-Android 5 recommended pattern) associated with the new adapter and the RecyclerView. The ViewHolder’s job is to cache the collection of row View objects. The findViewById( ) method to fetch View components gets expensive. In a ListView, this could happen a lot as the rows are continually rebuilt and redisplayed. The ViewHolder reduces that overhead.

In most case you simply extend the RecyclerView.ViewHolder class.  As you can see by the code below, the ViewHolder gets each row’s View components by id through the root view – itemView – passed to the constructor.

Fragment and LayoutManager

The RecyclerView is going to be displayed on a fragment.  A hosting fragment’s onCreateView( ) method is typically used to graphically initialize.  Therefore, it is in the onCreateView( ) method of the fragment that the RecyclerView is initialized.  You need a RecyclerView.LayoutManager to put items in the RecyclerView’s child views.  Unlike ListView or GridView, you can customize the layout of the child views (a point that will re reviewed below).  The RecyclerView here uses a simple LinearLayoutManager provided by the support library.  Below is the fragment’s onCreateView( ) with the RecyclerView initializing code.

Beyond the setLayoutManager( ) call, and association of the RecyclerView to its RecyclerView.Adapter, take note of the setHasFixedSize( ) method.  RecyclerView is about performance and display enhancements over widgets like ListView.  In this case, use this method to help increase performance of the display when size of the RecyclerView is not going to change – even though the rows/items will come and go dynamically.  As the documentation states:  “RecyclerView can perform several optimizations if it can know in advance that changes in adapter content cannot change the size.”

Hosting Activity

The activity, in this demo, is there host the fragment holding the RecyclerView.  It also starts/stops the stock price Service (and associate AsyncTask) and updates and forwards new price data from those to the fragment and RecyclerView.  Here is the important onCreate( ) method.

You can peak at the rest of the activity code on GitHub.

Additional RecyclerView Features

Beyond its performance improvements, RecyclerView comes with some display options that give it superior visual capability over the older components like ListView.  Custom layout management and animation are two such capabilities.

Layout Management

As mentioned above, when initializing the RecyclerView (see the hosting fragment’s onCreateView( ) method), you need to create and set the LayoutManager for the RecyclerView.  You can create your own custom layout or use LinearLayoutManager or GridLayoutManager (both subclasses of RecyclerView.LayoutManager) provided by the support library.  Simply swap out the layout manager to the RecyclerView and you have a different display.  Note the one line of code change below to use GridLayoutManager versus LinearLayoutManager.

gridrecyclerview

You can even use the layout manager to define the scrolling direction!

Animation

One of Lollipops considerable improvements is in the use of animation.  Not surprising then that RecyclerView allows for custom item animation.  You can determine how added, removed and update items get highlighted.  As a minimal example of this capability, you can use the DefaultItemAnimator that is associated to the RecyclerView by default, but customize the add and remove animation duration time when you initialize the RecyclerView.  This has the effect of exaggerating the coming and goings of the add and removed items of the view respectively.

Wrap Up

There are a lot of new features in Lollipop.  Stay tuned to this blog for more tutorials and reports about what you can find in this new release.  If you need help developing your Android application or if you need training in the basics of Android to get you started, let us help.  Contact Intertech today for Android consulting services or the next Android training class.

Like What You've Read?

Subscribe to the Blog.

Every Friday we send that week's content from our Developers via email. Try it out!

Some ad blockers can block the form below.

You have Successfully Subscribed!