Android: Make view on top of listview scroll together with the listview

∥☆過路亽.° 提交于 2019-12-03 03:24:42
Maria

I found a solution. Not sure if it is too elegant, but it works so will leave it unless somebody comes up with something better.

The view which I want to scroll together with the list is a custom view, which has to know about the list view. So I implement a setListView(ListView listView) method on it:

private int scrollY; //1
private Map<Integer, Integer> listViewItemHeights = new Hashtable<>();
public void setListView(final ListView listView) {
    listView.setOnScrollListener(new OnScrollListener() {  //2
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {} //3

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { //4
            View c = listView.getChildAt(0);
            if (c != null) {
                int oldScrollY = scrollY;
                scrollY = -c.getTop();

                listViewItemHeights.put(listView.getFirstVisiblePosition(), c.getHeight());
                for (int i = 0; i < listView.getFirstVisiblePosition(); ++i) {
                    if (listViewItemHeights.get(i) != null)
                        scrollY += listViewItemHeights.get(i);
                }
                scrollBy(0, scrollY - oldScrollY);
            }
        }
    });
}

Comment No.1: this is a variable letting me keep track of the current scroll position.

Comment No.2: setting a new on scroll listener to let my custom view know when the list

Comment No.3: this does not need to be implemented in this case.

Comment No.4: this is where magic happens. Note in the end I scroll my view by scrollY - oldScrollY, let me start with this bit first. oldScrollY is the kept scroll position, scrollY is the new one. I need to scroll by the difference between them. As for how scrollY is calculated I refer you to my answer here: Android getting exact scroll position in ListView, it is how the scroll position is calculated in list view.

for View of top screen you can add headerview so bind coustom layout as headerlayout of listview..so you have scroll same as listview...

View headerview = ((LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.track_footer_view, null, false);
    listview.addHeaderView(headerview);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!