John Petitto About Blog

A Padded Cell - Dealing with RecyclerView Measurements

In Android, a layout is composed from a hierarchy of views. Each view has a parent (up until the root view) and a ViewGroup can have child views. When a layout gets inflated at runtime, the framework measures each view according to its attributes about sizing and spacing. The result of a view’s measurements is also dependent on its parent and any sibling views.

RecyclerView is like most views in this respect but has some peculiarities. This comes down to a few reasons. RecyclerView sees regular updates by the Android team and sometimes its behavior with how it’s measured changes. And while it is a ViewGroup, its child views are provided indirectly through an adapter and managed by a LayoutManager. Lastly, its behavior to scroll sets it apart from most static views.

Fragments, Don’t Hurt Me

Here’s a screen I was recently working on for an app at work:

It’s built with a Fragment containing a ViewPager. Each page in the ViewPager is served by a FragmentPagerAdapter. Pretty straight forward stuff.

On first launch it works as expected, but if the enclosing Activity is destroyed, no pages get recreated by the FragmentPagerAdapter.

The Silliness of Nullability and Views

Since Google introduced the support annotations library, there’s been an increase in the application of the @Nullable and @NonNull annotations in APIs. It’s helpful in languages such as Java where optional values are not first class citizens. Static analyzers can infer at compile time if an object has the possibility of being null when passed to (or returned from) a method.

While the benefits of these annotations can certainly be helpful, they may also hinder users of an API. A great case in point would be that of the findViewById method in Android’s ActivityAppCompat class: