Search code examples
androidandroid-listviewandroid-scrollview

Scroll view at same time that ListView is scrolling


I have a RelativeLayout with a ListView and a custom View. I set the size of the custom view as the size of the ListView programatically. So I have the custom view on top of the ListView with both the same size. Obviously the ListView is not scrolling because the onTouchListener is on the customView. How can I make both scroll at the same time?


Solution

  • At the end I created a function in my custom view class with the ListView and the number of rows as parameters. Inside the view I setOnScrollListener to the ListView and I assign the position of my ListView while scrolling to my global scroll variable of the custom view. Like this

    public void setListView(final TwoWayView listView, int totalListRows) {
        totalColumns = totalListRows;
        for (int i = 0; i < totalColumns; i++) {
            listViewItemHeights.put(i,  (int) getResources().getDimension(R.dimen.column_width));
        }
        listView.setOnScrollListener(new TwoWayView.OnScrollListener() {
    
            @Override
            public void onScrollStateChanged(TwoWayView view, int scrollState) {
    
            }
    
            @Override
            public void onScroll(TwoWayView view, int firstVisibleItem,
                    int visibleItemCount, int totalItemCount) {
                c = listView.getChildAt(0);
                if (c != null) {
                    int oldScrollX = scrollX;
                    scrollX = -c.getLeft();
    
    
                    for (int i = 0; i < listView.getFirstVisiblePosition(); ++i) {
                        if (listViewItemHeights.get(i) != null) {
                            scrollX += listViewItemHeights.get(i);
                        } 
    
                    }
                    scrollBy(scrollX - oldScrollX, 0);
                } 
    
            }
        });
    
    
    }