[TUTORIAL] Android expansion and compression of items in a ListView. #AndroidDev


When I started to develop the first Android version of MyNextBus in London, I had to think about how implement the section management of different items types into a list. It was a great opportunity, at the time of the first writing, to use the framework’s widget called ExpandableListView. If you have never heard about that before, a quick look should solve any lack and make you more comfortable with what you’ll read below.

First Solution (v < 2.0.0)

As I said earlier the first attempt was based onto the ExpandableListView that manages for you, through an ExpandableListAdapter, the sections management using an instantaneous expansion/compression of the sections. That’s quite good because it saves you a lot of time that should be spent to implement the logic used to keep track of the sections and to distinguish between children and sections. If you check more in deep in the documentation, you can also managed indicators for both the items types but that goes far from this tutorial.

The first problem arose some days after the first build when my friend Massimo, that during the same period was developing the iOS version, showed me that, in just few lines of code, his app was able to expand and collapse smoothly with an animation, hiding/showing the indicator. So, at that time I tried to implement the same logic for the indicators using an ObjectAnimator that animates between 0-1 and viceversa the alpha value of the indicator.

The expansion and compression of the cells was quite messy because I had to keep track of the expanded element, the number of children and a lot of other stuff without having the entire control on the adapter and the way it cooperates with the ListView.
When the ExpandableListAdapter calls the getGroupView(…) it passes into a boolean value that lets you know if the group is expanded or not and that happens after the user interaction. Therefore, you cannot perform something like:

compress-animating-open => expand-animating-closed as a single transaction

So, after having tried a lot, I had fed up and I decided to avoid any animation because the management was making my code a lot dirtier.
MyNextBus has continue to grow in the last months without an expand/compress animation that has left in me a kind of sense of un-finished.

Refactoring (v >= 2.0.0)

Just few weeks ago, speaking again with my friend and complaining about the fact that on Android it’s a nightmare to perform animations, he said me something like “Stop to complain, do it!”. Hence, I decided to rebuild the entire application due to some other changes and I seized the opportunity to implement finally a proper expand and collapse with a simple ListView and a custom Adapter.

If you check the video you’ll notice two main parts:

  1. Normal Animation Time: as you can notice, since the data comes through, the app collapses the shown items and then expands the new ones magically and smoothly in their section (300ms).
  2. Slow Down Time: in the bookmarks section, as soon as I start to click one of the sections, the animation time slows down to 1200 ms and you are able to notice how the items smoothly collapse fading out and expand fading in.

Let’s have a look at some hints and snippets to manage the expansion and compression of list items.


  • ListView: I don’t have to explaing why obviously :)
  • CustomAdapter: maps sections to children and provides expand and collapse methods
  • ObjectAnimators(fade-in, fade-out, compress height to 1 and expand 1 to height)
  • BinarySearch: have you ever had an opportunity to use it? That’s the right time!
  • ViewTreeObserver.OnPreDrawListener: at the time of the item creation your view is not yet measured and if you try to obtain the layout params you’ll end up with an NullPointerException.

Mapping Sections to Children:

WHEN? onDataSetChanged()
WHY? because as soon as you fill the data to expand or collapse the adapter snapshot is no longer valid and needs to be refreshed.

Schermata 2014-03-15 alle 00.50.24

Discovering a section:

Arrays.binarySearch(sectionPositions, positionToCheck) < 0 ? TYPE_CHILD : TYPE_SECTION

Collapsing a section:
Schermata 2014-03-15 alle 00.48.05

Schermata 2014-03-15 alle 00.51.57

Expanding a section:

What I’m doing here can be recycled to compress the children that at the moment of the compression are out of the screen but those will appear during the animation.

Hence in your getView(…)

Schermata 2014-03-15 alle 00.58.22

What’s missing now?

If you try to develop a sample ListView with a custom adapter that performs similar stuff you’ll certainly notice that sometimes, especially when you have got lods of children, the new section that you are going to open disappears. This is due to the fact that at the time of the compression, the section that you have just clicked is shown below all the children and in order to fit the place that the will leave empty it will go out of the screen.
This can be fixed with some maths, scrolling your ListView to the position that grants the user to understand where he is. (I’ll definitely do that in one of the next versions of the app).

Thanks for your attention.

If you liked this post why don’t you spend a couple of mins sharing it with friends and colleagues? ;)


One year in #London, just the first chapter of a new book.

It has been one year since I left Italy, my friends and the warm nest of a family that never stops loving you.

Just this morning I received an email from my father who was asking me if I’m celebrating this wonderful day. I think that the biggest celebration is to be here; it doesn’t matter if it’s London, Paris, NY,… but the important fact is that I’m still here, fighting day by day for all those things that I like to do. In just one year a lot of things have changed in my mind, in my life and in my job. New horizons, goals and people have started to be part of this new life but at the same time all the “old” important ones have continued to follow me and support all my choices.

Far from that, I think that London is an amazing city. Sometimes it’s difficult to live in a place where people are always in a rush, think different and where the sun seems to be a little bit shy. But at the same time, the mix of different cultures, people and thoughts certainly gives a kind of different hints that create new flavors in your life. It’s a kind of blinking web that attract you day by day… more and more :)
As I said someone before my leaving, my plans for the future are not already defined but there are some things that I would definitely like to continue and to achieve.

After three months as a contractor for Telefónica, I started in March with Massimo Carli to work for DMGT(Daily Mail and General Trust), taking care of the legacy app of Daily Mail. It was like a nightmare because it was full of memory leaks, bugs, unsafe operations and not maintainable. During the summer we received the approval to rebuild it from the scratch and, doubling the users and the daily active loads, we have achieved a huge progress forward. It’s always difficult to satisfy thousands and thousands of different users but in my opinion we can be happy about our results that will certainly become better and better in the future.

At the Google I/O, in May, I had the opportunity to have in front of me a lot of the people those are building and setting the basis of the biggest and the most famous mobile OS in the World: Android. It was amazing when during the video of the keynote they show the 900.000.000 of activations. At the same time I walked through the main streets of San Francisco thinking how I am lucky and proud to be what I am. I’m just a point in the huge World’s shape but at the same time I’m one of the people who are trying to make it better dedicating all their efforts to achieve new goals and challenges.

During September I had the opportunity to be one of the speakers at AppsWorld and this was an important opportunity to see how, most of the times, patience, perseverance and stubbornness give the possibility to be a kind of referral point for someone else. During the same week there was the Droidcon and it was the opportunity to see people with whom I have worked in the prior months and to have some important hints by people from Square, Facebook and other famous companies.

There a lot of others things those happened during this intense year and it is just a bunch of them.

At the same time I have never forgotten where I come from and all the people who has remained in my life. I have never forgotten that some years ago the cancer has tried to kill me while I was throwing away my life for things that now look a little bit stupid and sneaky. I have never forgotten that my uncle died in front of me after some months of illness and therapies.

I have to thank a lot of people to be here today because without them I would never have done a lot of things and I would never have achieved what I am now and what I’ll be in the future:

  • My girlfriend with whom I’m living now; she is trying to get the best of me and to tolerate all my defects
  • My mother and my father those are proud of me and what I’m doing. They always made be sure I had everything that I needed and I’m pretty sure that nothing, except my happiness, will pay back them.
  • My brother who is complete crazy and who finally arrives here in holiday for his holidays
  • Massimo Carli and his family who have helped us to set up here in London and those have become our main friends here in the UK
  • My godfather and godmother those have been like friends and funs in all my adventures
  • All my friends

See you soon,

Time tables Verona 01/12/2012

Time tables Verona 01/12/2012

First time at #droidconuk :)

Hi all,
at the end of last week, after the Apps World conference, I went to the Droidcon conference here in London. It has been an event full of Android rock stars and full of good speeches like the one of Facebook, ProGuard and Gradle.

This time I don’t want to spend many words but only give some pics from that experience.

This slideshow requires JavaScript.

Geolocation Panel at #AppsWorld

Hi all :)
today with Ian Holt(Ordnance Survey), Carl Patridge(London & UK Bus Checker) and Josh Garnier(OpenTable) I have taken part into a panel, moderated by Shivam Gadhia(Novoda), about Geolocation for the Android platform at the Exhibition Center in Earls Court. Due to time limits we haven’t touch in deep every different aspect of the “new” Google Play Services but we have given to our gently audience a panorama around what this new service offers.

First of all, I would like to thanks all the people that have attended our panel and that have beared my accent. Then all the other panelists those have explained pretty well, thorough their working scenarios, all the problems, issues and solutions that they encounter every day during projects lifecycle.

Somedays ago I have read a post on a blog that accuses Android not being open source anymore and that now only Google has the full control on it through their magical Google Play Services: that’s not completely true. If you think about Android as an Operating System, the Play Services are a useful tool on the top of it and something that helps you dealing with complexities of the Android platform. In an ideal World, every device should have its Google Play Store installed, with every kind of related plugin, but, due to the open nature of Android, any different brand can customize and provide a different build.

In this way it’s quite difficult to have the Google Play on devices like Kindle or build those mount different stores for the apps.

So, when you are conscious that on most of the devices (90% on the market) around the World the services can be available, you should start to think something like:

  • Ok, I want to target that 90% without considering the other 10% taking advantage of the Play Services higher level API
  • I can take advantage of the Google Play Services and at the same time provide a customized(not necessarily worse) solution on the remaining 10%

One thing that I discourage you to do is to rely completely on the old location management for all the available devices. It’s true that Google Play Services aren’t available on every device and that managing all the possible edge cases can create some complexity, but at the same time, if you are able to use them, you’ll get rid of a lot of complexity to manage Geolocations issues. At the same time the device battery, other applications and your application as well will benefit of the big advantage of this new top layer tool; indirectly this means that you’ll provide a better experience for your users those will definitely be more happy!


“Just #Google it!”

I have started this post almost one month ago but I’m finding now the time to write something about one of the coolest companies in the World. I have never had the opportunity to work there but, as user and mobile developer, I have certainly noticed that in the last 15 years Google has changed the Web and in particular the life of billions of people.

Through products like its famous search engine, the Android OS, Google Plus, Chrome and dozens of other projects Google is gaining day by day more success and people that trust in its goals. If you think about that, every company tries to earn more money and to acquire more users but Google has something more: the desire to grow not only as a supremacy but as a vector of evolution for the entire World.

That’s not obvious because most of the people, especially in the IT world, tend to be more closed than opened to resources and tools sharing. Google thinks different and that’s the power and one of the aspects those have make it great!
I’m not saying that every product, every library and everything produced by this company is perfect or something that only a bunch of genius can produce but I would like to highlight the main purpose behind their business: make the life of everyone better.

Sometimes it quite difficult to maintain those kind of standards because if the other companies and competitors think in the opposite way, offering them a lot of useful tools can be quite painful. But if you consider the purpose of make the World better, that can be used to maintain alive the competition and the desire of discover new things.

As Android Developer, I’m really grateful to a company of this caliber because I have got the big opportunity to work in a world that without Google wouldn’t be so great and close at the same time. Working everyday on the mobile OS that is on the top of the edge makes me really proud and happy because, using a set of tools that’s offered for free, is giving me the possibility to do my own business but at the same time the possibility to work for something that goes beyond that.

There are a lot of big and good company all around the World but I’ll definitely continue to support Big G if they’ll continue in this way :)

A new #Android App for @MailOnline

In the last few months the MailOnline mobile team has completely rewritten from the scratch their Android application. Getting rid of the old code, we came across to a lot of iterations and problems those have forced us to re-think the entire background synchronization and the resource management. As one of the Android developer who has developed this version, I’m very proud to say that this version is definitely better, faster and smoother than the prior one.

This slideshow requires JavaScript.

The main features, improvements and changes that you’ll certainly noticed from the screenshots are:

  • Load more articles when you reach the bottom of a channel
  • Swipe down to sync news in the channels page (with progress percentage)
  • Swipe between different channels
  • A new drawer menu that will appear swiping from the left edge of your screen (enable in settings)
  • Share and comments feedback inside the articles
  • Shortcuts from article to main channels
  • Filters on data and image sync
  • Different priority and order for channels (based on your preferences)
  • Enriched FAQs screens

There’s still always something new to do and to improve but this can be consider a really good app that will allow thousands and thousands of people to read their favorite news paper.


Algorithms are fu**ing awesome!

If you have a quick look on Wikipedia you’ll find out that algorithms are procedures used to solve calculations and to process data.

When I was in university, one of my teacher has defined them like a receipt. Imagine that you have got dozens of ingredients. You have to mix them in order to obtain something that’s really tasty and that can be considered eatable.

From a certain point of view that’s true. Isn’t it? :)

One thing that takes a little bit of attention is the fact that the ingredients have to be selected and manipulated following particular procedures otherwise you’ll obtain a food that it something “similar” to what you are expecting.

One week ago, I was reading a problem on Codility that at the beginning was appearing really… really… EASY PEASY!
That’s the greatest mistake that you can do! It doesn’t exist a problem that is simple… otherwise it’s not a problem ;)

After that assumption, I tried on my favorite editor to solve the problem and it “was failing some tests” (if it doesn’t cover any case it’s wrong).
I misunderstood the fact that my solution wasn’t considering entirely the input.

Hence I decided to focus on the velocity of the execution because maybe some loops + if statements were speed down the execution.
That’s another problem: don’t focus on velocity at the beginning. You’ll incur in a lot of mistakes and the problem will become more complex than expected.

At that point I decided to drink a huge cup of strong Italian coffee. “What am I doing?!?!? That’s not the way!”
This was not the idea that solves all your problems but a kind of ray that was saying me that I should start to think instead of trying a feasible solution .

At the end that’s the result:

Detected time complexity: O(N * M * log(M) + N * log(N))
Score: 100 of 100

…getting back to my teacher’s words, when you are sure that your solution works, you should start to think “Can I do something more?“.

Most of the time the solution is YES! OF COURSE!

Leaving that’s long and boring introduction I think that algorithms are not only a way to solve problems but a tool that allows us, not only geeks or nerds, to find other possible better solutions or to confirm that our one is the best one.
So, if you have a look at the icon, that is taken by the Princeton website, you should consider the opportunity to think a problem as something that has to be solved through organized iterations not only as an intuition.

#Java @nnotations

“Annotations, a form of metadata, provide data about a program that is not part of the program itself. Annotations have no direct effect on the operation of the code they annotate.

Java Tutorial – Oracle (Sun)


public @interface <name>{

<type> <method_name>();

<type> <method_name>() default <value>;


  • @Retention annotation specifies how the marked annotation is stored:
    • RetentionPolicy.SOURCE – The marked annotation is retained only in the source level and is ignored by the compiler.
    • RetentionPolicy.CLASS – The marked annotation is retained by the compiler at compile time, but is ignored by the Java Virtual Machine (JVM).
    • RetentionPolicy.RUNTIME – The marked annotation is retained by the JVM so it can be used by the runtime environment.
  • @Target annotation marks another annotation to restrict what kind of Java elements the annotation can be applied to. A target annotation specifies one of the following element types as its value:
    • ElementType.ANNOTATION_TYPE can be applied to an annotation type.
    • ElementType.CONSTRUCTOR can be applied to a constructor.
    • ElementType.FIELD can be applied to a field or property.
    • ElementType.LOCAL_VARIABLE can be applied to a local variable.
    • ElementType.METHOD can be applied to a method-level annotation.
    • ElementType.PACKAGE can be applied to a package declaration.
    • ElementType.PARAMETER can be applied to the parameters of a method.
    • ElementType.TYPE can be applied to any element of a class.
  • @Inherited annotation indicates that the annotation type can be inherited from the super class. (This is not true by default.) When the user queries the annotation type and the class has no annotation for this type, the class’ superclass is queried for the annotation type. This annotation applies only to class declarations.

Read the rest of this entry

#IO13 When the magic becomes reality!

Just some pictures from Google I/O.

This slideshow requires JavaScript.


Quick trip to #Oxford

Hi to all :)

If you have never been to Oxford or if you have really appreciated this beautiful city, you can find here some pics!

For all Nerds, I’ll back as soon as possible because in the last few months I had a lot of changements and I’m actually adjusting my #Android libraries.

This slideshow requires JavaScript.


Get every new post delivered to your Inbox.

Join 405 other followers