Android Horizontal ListView

Due popularity, I have decided to create a GitHub repo for this project. Please checkout the code at: https://github.com/dinocore1/DevsmartLib-Android Pull requests are welcome! ;-)

Licensed under MIT License Copyright (c) 2011 Paul Soucy, (paul+blog@dev-smart.com)

The Android API seems to be lacking a Horizontal ListView widget. Basically, what I needed was something exactly like the Gallery widget but without the center-locking feature. After much googling (and finding dead ends like this or this), I eventually came to the conclusion that a Horizontal ListView simply did not exist. So I built my own…

My Android Horizontal ListView implementation has the following features:

  • Subclass AdapterView so I can make use of adapters
  • Fast – make use of recycled views when possible
  • Items are clickable – (accepts AdapterView.OnItemClickListener)
  • Scrollable
  • No center-locking
  • Simple – is that so much to ask?

If you find this helpful, let me know, I would love to hear your feedback.

How to use:
Horizontal ListView is ment to be a drop-in replacement for a standard ListView. Here is some quick demo code to get you started:

res/layout/listviewdemo.xml:

res/layout/listitem.xml:

Download code from GitHub

old download link: Horizontal Listview (14441)

Changelist
1.5:
adapter.notifyDataSetChanged() now saves position in list instead of starting at begining

1.4:
Added code to respond to adapter.notifyDataSetChanged()

1.3:
added mScroller.forceFinished(true); to the onDown function of mOnGesture so the user con stop the scroll on tap.

183 thoughts on “Android Horizontal ListView

  1. Hi,

    This tutorial is nice and it is exactly what i needed. Thanx a lot. Is there a way to bring snap factor to the same code?

    1. halo, I find this useful, and it is perfect if I can add a “onLongClickedListener” on the item of the view, can somebody help me?

    2. hi, this is the code which i need thanks,
      but the Horizontal scrolling is not smooth.. as compare to other gallery scrolling ..
      pls help me out from this problem

  2. Hello,
    i use your implementation and i have some problems, i want to scroll from bottom, so i change the position with scrollTo method but it’s not work for me:
    HorizontialListView listview = (HorizontialListView) findViewById(R.id.listview);
    listview.setAdapter(mAdapter);
    listview.scrollTo(getCount()-1);
    mAdapter.notifyDataSetChanged();

  3. nice effort :)
    btw i have tried your horizontal list but I need to populate horizontal list view in a vertical list view and I have made two adapters for that one is for populating listview and another one is for horizontal listview but unable to get any view :(
    any Idea how can I achieve my goal

    1. I had the same issue, and had to eventually force a height onto the HorizontalListView to get it to show, my items where exactly 100dp tall, so instead of wrap_content, set it to 100dp.

      1. Yes,I tried it, I must force a fixed height instead of wrap_content when using tow HorizontalListView in one layout. What I should do if I want to use the “wrap_content”

  4. finally i have succesfully inflated your horizontal list view in List view … but the horizontal scroll is not very much smooth :(
    can you help me further when i scroll horizontal list it will move upward too .. how can i reseolve this issue

  5. I have the view working shown as above. but how do i go on about if i want each item to be sized to fit screen so only one item is show at a time.i tried several variations of fill_parent and match_parent none worked. so please help

  6. Hi, nice helpfull post but I have a question.
    I compare it to ListView ,I find a question that Horizonl ListView doesnot implement onKeyDown(envent) and how to implement it?

  7. Hi,
    Thank you very much for your library. I’m using your lib and have a question. My list view item is a image with a checkbox on it. I can check it already but when I scroll out and scroll again, the state of checkbox is uncheck. May be because the recycle view. How can I solve it? Is there any link about this?

  8. It’s pretty usefull lib but sometimes it’s scrolling is stuck in the middle of the horizontal list view evenif there lot more items after that.Please help.

    Regards,Green

    1. +1 same issue for me. When I change my orientation to landscape mode and back to portrait mode, my adapter does not scroll

    2. what i’m seeing is that the onLayout method is incorrectly saving the mNext and mMax values. After orienting my device back to portrait mode, it’s running into mNext >= mMax every time

  9. I’m trying to use this lib but i got a problem related to onScrollListener. I want to add more item when user scroll to the end of the list but i found out that this lib doesn’t support onScrollListener.

    Anybody can help me?

    1. i got the same problem.i want to scroll the list when i pressed a button.but i can’t find any way to do it . if i add an view.scrollTo(x,y),it looks like scrolled.but after that ,the item click position is wrong ,and the list scrolling seems like stuck,how can i fix it?

  10. I m trying to use this lib. Any idea as to how to add a white Horizontal ListView Separator. I tried doing in android:divider=”#FFCC00″ android:dividerHeight=”1px” in listviewdemo.xml. But it doesnt work. Any help will be appreciated.

  11. i’ve provided a temporary fix by adding the following line to onLayout (for those that are having issues with orientation changes):

    if (mCurrentX == 0 && mNextX == 0 && mMaxX == 0)
    mMaxX = Integer.MAX_VALUE;

  12. Hi,

    I’m using your HorizontalListView inside a standard ListView (if anyone is still strugging – set fixed height of HorizontalListView to see anything ;-) ).

    I have one small problem – I was trying to get preview of combined lists in Eclipse ADT using xmlns:tools=”http://schemas.android.com/tools” and tools:listitem=”@layout/viewitem”, but HorizontalListView have hard time displaying itself in there.

    Maybe someone knows, what needs to be added for it to display correctly? (I already figured out, that adding

    if (!this.isInEditMode()) {
    mGesture = new GestureDetector(getContext(), mOnGesture);
    }

    in HorizontalListView’s initView() method removes the “com.devsmart.android.ui.HorizontialListView failed to instantiate.” errors, but what do I need to do next to get preview of the items?

    Best regards,
    Damian

  13. How HorizontalListView is different from HorizontalScrollView.?

    Sorry if its a silly question, but im new to android, and have only started it.

    1. You have to preload all items into HorizontalScrollView. HorizontalListView will load items on demand with an adapter therefore optimizing memory usage.

  14. Thanks for the code, it works brilliantly, just wondering if anyone can help, I would like to add different images. At the moment the code is only displaying the same image 3 times.

    Also is there any way that I can get the small little dots at the bottom of the images to scroll through the images.

  15. Hi Paul,

    I’m working with your HorizontalListView class. I’m trying to center the items with gravity but I can’t find the way. Every item is a RelativeLayout.

    Can you help me, please?

    1. Hi Francesc,

      I am having the same issue as well. Were you able to find a solution for this ? All my items are right aligned … So if i have only one or two items in the list, it looks really bad as it is right aligned.

      Prashanth

  16. I am using this widget but the list item is taking up the whole width of the screen instead of the defined size in layout. Please help to resolve this issue.

  17. Hi, have anyone else noticed lags during scrooling? I thing it is due to requesting layout on each scrools step which is wrong. You should only invalidate instead and and move removing views/filling into compute scrool method.

  18. Hi, it’s a useful lib for me, thanks for sharing!!

    I’m writing a APP which will publish in google play,
    Is it okay to use your horizontal listview in my APP?

  19. Thanks for the great library. no matter what the size of icons i use , the images stretch and look ugly.how do i adjust the height of the HSV and the icons in it.

  20. Hi. Thanks for your code :)
    By the way, I have a question.
    I made a horizonatal listview with your code.
    I made width of each item is fill_parent.
    I want to made this scroll one by one just like pager. is there any suggestion?
    i’ve already tried onTouch method but it doesn’t work perfectly.
    Thanks.

  21. You understand thus significantly relating to this subject, produced me in my opinion imagine it from so many varied angles. Its like women and men don’t seem to be involved until it’s one thing to do with Lady gaga! Your own stuffs nice. At all times take care of it up!

  22. Hi,
    I am using ur Horizontal listview in my app. In my app there is a view slider like the facebook. when i click a button the view slides. this view contains the horizontal listview, when i scroll the horizontal listview the entire view start scroll from the starting position. is there any way to stop scrolling or disable entire horizontal listview?

  23. Hi,
    First of all thank you for your great library. My problem is that I am not able to make the listview vertically centered. Would you please explain how can I do that?

    Thanks in advance.

    1. hi hazir,
      This may help you. try this, use this horizontallistview inside a linearlayout and add this line to your linearlayout.
      android:gravity=”center”.

      1. Hi, I’ve tried your solution but it does not work! My xml code is:

        Items are all top aligned, so they are not centered at all!
        What can I do?

  24. I want each list item to has its own height and I want width of each item to be (screen width – 20dp).. Also, I want divider between each list item.. I spent couple of hours yesterday, but I could not do this.. Can you help me, how to do this!?

    1. For “Error inflating class linearlayout”,
      just fix to in listitem.xml
      (And , )

      Also, “R.layout.viewitem” should be “R.layout.listitem”.
      And I change “HorizontialListView” to “HorizontalListView”, too

      1. // xml tag was canceled by wordpress… so I post it again
        For “Error inflating class linearlayout”,
        just fix to in listitem.xml
        (And , )

        Also, “R.layout.viewitem” should be “R.layout.listitem”.
        And I change “HorizontialListView” to “HorizontalListView”, too

  25. Hello everyone. I manage finally to make the wrap content work. This is the code missing:

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int firstChildHeight = 0;

    int size = getChildCount();

    if (size != 0)
    {
    for (int i = 0; i < size; ++i)
    {
    final View child = getChildAt(i);

    if (i == 0)
    {
    firstChildHeight = child.getMeasuredHeight();
    }
    }

    setMeasuredDimension(widthMeasureSpec, firstChildHeight);
    }
    }

    Let me know if it works for you and if you have any comments about it. Thanks!

    1. Thanks mate. It’s working well for me and is nice approach. I have some comment about your code.
      If you’re just going to measure height by first child item, I think you don’t need to check whole child, which means you don’t need for-loop.

      View child = getChildAt(0); // it will return null if the position does not exist.
      if(child != null){
      setMeasuredDimension(widthMeasureSpec, child.getMeasuredHeight());
      }

      Or if you thought about set height by tallest child’s height, you’d better compare each child’s height in the for-loop.

      int childHeight = child.getMeasuredHeight();
      if(firstChildHeight < childHeight){
      firstChildHeight = childHeight;
      }

      p.s: I still see list view occupying whole height in xml when I design layout. Do you have any idea about this?

    2. Thanks so much for this!

      I wasn’t able to get my horizontal listview to center horizontally in its parent (it was always filling the whole screen and filling from the left), so I just added a line to your code here to measure each child’s width, add them up and set the measured width and it worked great!

  26. Thank you,this code is best! But,i have some problems. i want only horizontallistview.how can i do that? thanks in advance. i’m beginner in android

  27. Even better, Check out this code done by inazaruk https://github.com/inazaruk/android-dev-smart-lib/blob/65d68269d5f453d9b590a02369a04add96ae1d9c/devsmartlib/src/com/devsmart/android/ui/HorizontalListView.java. Now works even when it is in a vertical scrollview. I would just add one last line of code in the method onScroll:

    /*
    * Now’s a good time to tell our parent to stop intercepting our events! The user has moved more than the
    * slop amount, since GestureDetector ensures this before calling this method. Also, if a parent is more
    * interested in this touch’s events than we are, it would have intercepted them by now (for example, we can
    * assume when a Gallery is in the ListView, a vertical scroll would not end up in this method since a
    * ListView would have intercepted it by now).
    */
    getParent().requestDisallowInterceptTouchEvent(true);

    Hope it helped.

  28. For whose facing right aligned problem, do the follow fix:

    Change:
    mScroller.fling(mNextX, 0, (int)-velocityX, 0, 0, mMaxX, 0, 0);

    To:
    //mScroller.fling(mNextX, 0, (int)-velocityX, 0, 0, mMaxX, 0, 0);

    Change:
    if(mNextX mMaxX) {
    mNextX = mMaxX;
    mScroller.forceFinished(true);
    }

    To:
    if(mNextX mMaxX) {
    mNextX = mMaxX;
    mScroller.forceFinished(true);
    }
    }

  29. Thanks for the widget. It was necessary.

    But I think the “notifyDataSetChanged” is facing some problems: the thing is that, when being called, is removing and re-creating all views in the adapter. This, in large set of items, can lead to memory leaks with subsequent out of memory errors.

    This is, in fact, what was happening to me. I tested it using the common ListView, and this leaks are not happening, since the views aren’t re-created when is not needed. A small change in one of the views, means that all getView are called, and being worst, with convertView = null, so a new view is created for each item.

    Has anyone faced this problem and found a solution? I am still trying to modify the code to manage the notifyDataSetChanged like ListView does it but it does not seem to be trivial.

    Thanks.

  30. I have multiple HorizontalScrollViews inside a ScrollView. Horizontal scroll isn’t smooth at all. I have to scroll almost perfectly horizontally for scrolling to work.

    Link to screen: http://i.stack.imgur.com/DcFWE.png

    How can I disable vertical scrolling when scrolling horizontally?
    Or is there any other solution to this problem?

    Thanks.

  31. Hi,

    Thank you for this great widget! It sure was needed!

    I have a problem that occurs from time to time: When I scroll very fast through my HorizontalListView (swipe once or twice very hard on the screen), it scrolls through almost all the list but it stops at the end, two or three items before the end of the list and gets stuck there. I can scroll again to the left but I can’t seem to get it to scroll further to the right, to the end of the list, past this “stuck point”.

    Sometimes the stuck point isn’t even the right border of one of the items, but somewhere in the middle of an item, and it appears as if the HorizontalListView cuts the right side of this stuck item.

    Has anyone come across such a problem?

    Thank you

  32. Hi,

    I have one big issue with the HorizontalListView, It is occupying the complete layout height even though i specify layout_height as match_parent. As a result i find difficulty in using this in smaller devices

    Here is my main layout

    You can see i have specified layout_height of com.devsmart.android.ui.horizontiallistview as wrap_content. But, the TextView which i have specified after the HorizontalListView is not displaying …. Please help me in solving this issue

    NOTE: If i fix the height of the HorizontalListView then it is working fine ..

  33. the views are not getting updated after being added as a list item. Suppose i change the height of a layout in the list item it doesnt shows up ??

  34. i want drag and drop functionality in horizontal listview in my app.so can anyone help me to implement drag and drop functionality in android horizontal listview.?? Thanks in advance.

  35. Great Work… loved it!

    I am now trying to change the position of the list (move to a huge number), like I could do with a normal listview using setSelection(100000). There is no implementation yet. Also scrollTo() is not applicable since android would be lost drawing views and never reaching the target position. Any idea?

  36. Hi,

    Thanks for the implementation. I’m currently using this code as the base to implement circular Horizontal List View, any suggestions ?

  37. Hi, I just wanted to share a problem I had with HorizontalListView. I have a ViewPager which works as a gallery through which I can swipe left/right and a small HorizontalListView with image miniatures inked to this ViewPager. When I change a page in ViewPager I want to use ‘scrollTo(…)’ to scroll to a miniature linked to the big picture and call notifyDataSetChanged() on the adapter (I apply shadows to nonselected miniatures). The problem I had was that notifyDataSetChanged stopped the scrolling… And the solution was to extract method initValues() from initView() and in onLayout method to call that in ‘if(mDataChanged)’ instead of initValues. The ‘initValues()’ does not contain
    mScroller = new Scroller(getContext());
    mGesture = new GestureDetector(getContext(), mOnGesture);

  38. hey,at first,i would like to say thank you,this horizontal listview is helpfull to me.But,i got a problem with using this listview,i want to add a onTouchListener to the item which is inside the listview,but i can not do that,would you like to help me if you got some time,thank you,again.

  39. How can I add images dynamycally? (instead of taking the ones in drawable-ldpi folder as it does the example)
    Thanks

  40. Hello,

    It’s a great ui control! Appricate it! My question is I need make some customization on style of item row when user pressed it. Even my style is working on normal ListView control but it doesn’t work on HorizontalListView.

    item_row.xml


    item_row_highlighted.xml


    colors.xml

    #ffba40

    It worked on normal listview but doesn’t work on your custom listview … What’s the problem? Any suggesstion?
    Thanks.

  41. I have a question , I don’t found any thing that use can use as adapter.setSelectedItem(int itemNo); how to achieve that?

  42. Hello!

    First of all, thank you very much for the code, I’ve been looking like crazy.

    Could I indicate how to perform the movement by HorizontalListView, but through two buttons instead of dragging your finger?

    Thank you very much!

  43. Good one.

    But horizontal scrolling is not smooth when the view is inside Scroll View (Vertical). Is there way to give precedence to horizontal scroll.

    Also the glow effect is missing when the end is reached.

  44. Pingback: Web Tasarımı
  45. Your implementation is nice. Can u clear my doubt?
    How can i use setSelection(position) in your Horizontal List view?It doesn’t work.

  46. i want to use setSelection(position) in Horizontal List View.
    but it is not working. Is there any other way to imlement this functionality?
    Please reply asap.

  47. Beneficial info and excellent design you got at this point! I want to thank you for writing your ideas and putting the time into the stuff you publish! Great perform!

  48. Great work, thanks for publishing, been looking for this for ages, however, I need a listener or a way to add a footer, so I know when to load more items to the list.

    Any1 figured this thing out already?

  49. I am not sure if your ListView does this or not.

    Does it scroll horizontally & vertically?

    For example, web browser screen allows horizontal and vertical scrolling.

    Thanks,
    Ashok

  50. Hi, i try to use your lib, but! it have big problem, i set android:layout_width=”match_parent”
    android:layout_height=”wrap_content”
    BUt list still think that he have all empty space bellow! and i cant add any view bellow it…

    1. The issue seems to be the way the author measures the child view.

      In the function addAndMeasureChild use MeasureSpec.EXACTLY instead of MeasureSpec.AT_MOST for a better effect.

  51. how to implement
    horizontallistview.setOnScrollListener(new OnScrollListener() {

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
    int visibleItemCount, int totalItemCount) {
    // if (++firstVisibleItem + visibleItemCount > totalItemCount) {
    if ((totalItemCount – visibleItemCount) <= (firstVisibleItem + visibleItemCount)) {
    //load more content
    offset=offset+12;
    if(offset<=36)
    popuplist(offset);
    else{
    lv.removeFooterView(listfooterView);
    }
    }
    }

    @Override
    public void onScrollStateChanged(AbsListView arg0, int arg1) {
    // TODO Auto-generated method stub

    }
    }

  52. either listview.setSelection(arg2); nor listview.requestFocusFromTouch(); is working. i need to focus the selected item and i am doing porformItemClick also but the view is in hidden from screen (mean next image has to be shown when i scroll my other gallery or relevant to the image)

  53. Hi, first of all I just wanted to say great job on this. It works great. I have an issue. I’m trying to give focus to each image so the user can scroll left or right just by using the arrows on the keyboard, but doing setFocusable(true) is not doing the trick

  54. Hello, It is so helpful for me, but when I use your code it is showing me an error on

    HorizontialListView listview = (HorizontialListView) findViewById(R.id.listview);

    It is asking me to create a class of HorizontalListView. Do I need any jar file for this.?

    Thanks.

  55. Hi ,

    Works well. Very well implemented.

    I have a question regarding horizontal view layout parameters.

    I am doing exactly like what u are specifying , horizontal layout is using whole space of the screen and any views below it are not displayed.

    Can you please tell me what could be work around ??

  56. Thank u for help.My problem is that listview ites aren’t highlighted according to the selector.And to set choice mode like normal listview there is no option.

  57. I add 2 HorizontalListView in to Layout but it show 1. I can’t see other view below this. i set layout-height=wrap-content.

  58. Hi I need an urgent solution. This thing is not working with fragment. The get View is called correctly but the views are not being displayed. Can you please help me on this ?

  59. This doesnot work with fragment. The view are not being drawn on the screen. Where as it is working with the activity

  60. hello ,
    I have to implement one image on one scroll . Suppose i scrolled at right side then
    image will be getting from web service and this image will be the displayed .

    But how to find direction of the scrolling .

    plz help me out . Thanks in advance .

  61. There is a small bug in the listview concerning the mMaxX value. It occured when i used the scrollTo method and scrolled from 0 to the last element. mMaxX had to little value (exactly the width of the amount of fitting elements in the view [e.g. in landscape 7xchild-Width & 4xchild-Width in portrait mode]) and therefore the list ended several items before the last element. But as a matter of fact the mNextX had the correct value. Therefore the bug is in the fillListRight()-method. Please add this code snippet. ;)

    private void fillListRight(int rightEdge, final int dx) {
    while (rightEdge + dx < getWidth()
    && mRightViewIndex mMaxX) mMaxX = mNextX;
    }

    if (mMaxX < 0) {
    mMaxX = 0;
    }
    mRightViewIndex++;
    }
    }

  62. Sorry comment was somehow cropped and my posted method is incomplete :(
    (please don’t copy the above code)

    private void fillListRight(int rightEdge, final int dx) {
    while (rightEdge + dx < getWidth()
    && mRightViewIndex mMaxX) mMaxX = mNextX;
    }

    if (mMaxX < 0) {
    mMaxX = 0;
    }
    mRightViewIndex++;
    }
    }

  63. Sorry for tripple post … please just replace this in your fill list right method -_-
    if (mRightViewIndex == mAdapter.getCount() – 1) {
    mMaxX = mCurrentX + rightEdge – getWidth();
    //this fixes the bug with the mMaxX-value
    if(mNextX>mMaxX) mMaxX = mNextX;
    }

  64. I want to add divider and listview selector in our horizontal listview but it is not visible in xml layout.Please help me…

  65. Hi Pro. That’s good. But i want it work in v7 ActionBarActivity not Activity. But it’s error. So how can run it in v7. Thank you.

  66. hi I imopted ur libr but In my project giving error ..when i imported

    import com.devsmart.android.ui.HorizontialListView;

    giving error create a class

  67. i m using horizontal listview also vertical scroll view is it possible when clicking horizontal listview the scroll get lock to make horizontal scroll better and vice versa

  68. How do we attach click listener to child’s child. ? I have one image view and a text view inside child view. I need to attach click listener to image view and to text view too. How do i do?

  69. Thank you very much for sharing the HorizontalListView. I’ve been trying to implement this code and I’m having some trouble getting the HorizontalListView(HLS) height to wrap_content. I’m passing an ArrayAdapter to the HLS and when I populate the adapter with data and call notifyDataSetChanged(), there is no change in the height of the HLS. The height of the HLS doesn’t expand at all. If I set the height of the HLS explicitly in the xml layout then I can see the list items, so the data is clearly there. How exactly would you fix this issue?

Leave a Reply

Your email address will not be published. Required fields are marked *