2010/11/25

Gallery, clicking and selecting

Android SDK includes a nice-looking component named Gallery.
It's supposed to provide you with functionality of flickable view-changer.
It get's an BaseAdapter and displays views it receives.
All good until you actually start using it.

First issue: 
setSelection(index, animated) method ignores the second parameter. There's no 'todo' anywhere, 'deprecated' or even acknowledgement from Google. It just doesn't give a crap what you pass there. It always navigates to your item without animation.
Now let's say that I want to change items in the gallery every X seconds. How can I make a pretty animation showing this lovely change? By hacking the bastard. Basically, the animations are initiates by the Fling motion that the component detects. If you simulate the correct fling - you will get the View flip animation.

gallery.onRealFling(null, null, -800, 0);
Here's a tricky part - the X velocity parameter needs to be adjusted per application, because to fling a larger view, you need a bigger velocity. So play with that value until you get a smooth transition.


Second issue:
Items inside the layout that you return in your adapter cannot receive click events. They just can't. No good reason for it, but someone botched up the bubbling up of mouse events in the Gallery, so now you can't have clickable items. If you set any one of them as clickable - the gallery stops handling dragging.
But fear not - you can fix it!
The solution is as follows - you add a touch listener to the gallery, and catch a Single Tap event (I did it with gesture listener), to differentiate it from the dragging that the gallery needs to handle.
Then, from the the location of the touch event, you can calculate where exactly inside your sub view the click was made - and from that you can handle the actual click.

Here's the code: