Pages

Friday, October 3, 2014

ItemsViewGroup - simplify creation of custom layouts with views recycling

ItemsViewGroup
Today I want to share a custom ViewGroup which I developed a while ago, before the announcement of the RecyclerView from the Android L! ;-)

https://bitbucket.org/NxAlex/itemsviewgroup

ItemsViewGroup is an Android ViewGroup to simplify creation of custom layouts with support of views recycling and gestures support like scrolling, flinging, etc. Views cache supports multiple views types, so your custom layouts can have different views and for each view type there will be a cache.

The idea behind ItemsViewGroup is simple: encapsulate layout agnostic things like views recycling (similar to what ListView does) or common touch interactivity, and delegate a specific items layout to subclasses.

Samples
Creating a custom layout on top of the ItemsViewGroup is fairly simple. Basically all you need to do is to implement layoutItems method and provide items data in some way (e.g. via Adapter). Optionally you may want to specify a scroll range, items padding, etc.

As an example there is a GridView implementation. GridView is a ViewGroup that displays items in a two-dimensional grid with horizontal and vertical scrolling. It behaves similarly to a default Android GridView, however in addition it is able to scroll in both directions (not only vertically).

Also it supports rows and columns of different sizes. Each item view is measured to fit a grid cell.

There is a video demonstration of the GridView in action.


Note: the video is recorded with the adb shell screen record command so the frame-rate is pretty low (~15 fps). That is why the video looks not so smooth as the view really is. I recommend to run the sample to see how fast and smooth it is. There is a repository contains sample sources as well as the compiled apk.

Extensibility
GridView is easily extendable as well as ItemsViewGroup. Let's say we need to have a view with vertical scrolling and horizontal space evenly distributed among grid columns. So it looks like the default Android GridView. All we need to do is to override getColumnWidth method:
@Override
protected int getColumnWidth(int column) {
  return getMeasuredWidth() == 0 ?
         super.getColumnWidth(column) :
         // calculate evenly distributed horizontal space with respect to padding
         (getMeasuredWidth() - itemPadding) / data.getColumnsCount() - itemPadding;
}

And voila, now we have a VerticalGridView!

The same trick works for a HorizontalGridView to have a view with horizontal scrolling and evenly distributed vertical space among grid rows.

It's easy to create different types of layouts, not only grids and lists (which are essentially grids with just 1 column). For example, by having a variable number of columns per row we can have something interesting like:


Feel free to check out the ItemsViewGroup repository and contact me if you need some help.

No comments:

Post a Comment