Using a widget.Gallery to display a horizontally scrolling list of items. I’ve implemented paging in the gallery with what seems to be the standard technique: subclass Gallery and implement:
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (velocityX>0) {
onKeyDown(KeyEvent.KEYCODE_DPAD_LEFT, null);
} else {
onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, null);
}
}
When tapping the gallery, I fade up next and previous image buttons. When clicking these, I want the gallery to animated to the next/previous page, respectively. I’ve tried calling onKeyDown from my next-button handler, but strangely this has no effect.
AbsSpinner has setSelection(int position, boolean animate) but animate is ignored in Gallery.
Exactly what toucan said, but to elaborate further (comments limits are too short):
The problem seems to be the fact that the
Gallerydoesn’t let the user scroll if no children exist in that position yet.scrollToChild()is the culprit when trying to inject the event:Interestingly, if you fling the gallery with your fingers, it will cause the child to be created. Then, if you let go of your finger (going back to the original position), and then press the button that activates the
onKeyDowninjection, it will work flawlessly – because the child is there.Unfortunately there’s no real solution since everything is private in that class. The only solution is to use
setSpacing(-1)or something in the gallery, so left and right children are always created and visible, but just behind the currently selected view.As a footnote, I’m really baffled as to why everything is private in that class (or in any other of the Android widget classes for that matter). This is one of those things that could easily be fixed with some small code change.
Edit (Aug 2012): For future reference, rather than trying to use a Gallery for this kind of pattern (when you want the user to swipe between different items while only one of them is visible), it’s much better to use the Android’s compatibility package’s
ViewPagerclass. In my opinion, the compatibility package is not as celebrated as it should be (it took me a while to get notice of it). For developers targeting Android 2.x+, it’s a godsend.