Tuesday 20 March 2012

Using gallery as Horizontal list view in Android

The question has already been asked on Stack Overflow: http://stackoverflow.com/questions/3877040/how-can-i-make-a-horizontal-listview-in-android

We have had a real problem getting a horizontal list view in one of our mobile applications and were initially planning to come up with one of our own. We have even come across some implementations online for Horizontal List View as a reusable component. But when tried understanding it more, we came with a approach where an existing Gallery component can be used as horizontal list view and that too with little efforts.

Gallery by default center locks the element selected and, unfortunately, is not extendible to even override that behavior. So the alternative way is to adjust the margin. Here is a sample implementation:

public class CustomGallery extends Gallery{
.
.
.
    public void setMargin(Context ctx, int width) {
        LinearLayout.LayoutParams localLayoutParams =
                        (LinearLayout.LayoutParams) getLayoutParams();
        localLayoutParams.leftMargin = (width - tileWidth - 2 * gapBetweenTiles) * -1;
        setLayoutParams(localLayoutParams);
       
    }

.
.
.
}

That is just a sample implementation, you can have it in your own way keeping the approach same :-)

Good Luck !!!

1 comment:

  1. Hi!
    How did you managed this method to be called? I made exactly as you wrote, but method doesn't even called in my custom gallery, and gallery is still centerlocked.

    ReplyDelete