Search code examples
androidandroid-listview

Detect Top of ListView Scroll


I want to detect the Top of List view and i am using this method.

@Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (firstVisibleItem == 0)
                    swipeRefreshLayout.setEnabled(true);
                else
                    swipeRefreshLayout.setEnabled(false);
            }

This works fine, but the problem is I have attached the Header View to list as well. When I scrolled up, as soon as the first item is visible(not the Header view) it calls pull to refresh of list view. How can i detect that the List's Header is completely visible. My List View Is

View imageSlider = inflater.inflate(R.layout.image_slider_layout, null, false);
findViewById(imageSlider);

mPullRefreshListView.addHeaderView(imageSlider);

private void findViewById(View view) {
        mViewPager = (ViewPager) view.findViewById(R.id.view_pager);
        mIndicator = (CirclePageIndicator) view.findViewById(R.id.indicator);
    }

Solution

  • hmm, Interesting answer lies in onTouch listener rather then onScroll, see the implementation below, it exactly tells u when header is completely visible, you can refine the logic further.. its just a quick implementation form me.

        // Set a on touch listener for your list
        mList.setOnTouchListener(new OnTouchListener(){
    
            @Override
            public boolean onTouch(View v, MotionEvent event) {
               // get the top of  first child
                View mView = mList.getChildAt(0);
                int top = mView.getTop();
    
    
                switch(event.getAction()){
    
                case MotionEvent.ACTION_MOVE:
                    // see if it top is at Zero, and first visible position is at 0
                    if(top == 0 && mList.getFirstVisiblePosition() == 0){
                        Toast.makeText(MainActivity.this, "Header Item Visible", 
                                Toast.LENGTH_SHORT).show();
                    }
                }
                // dont forget to retrun false here
                return false;
            }
    
        });