5

I want to determine if my Gridview is scrolled to its top.

Right now I'm using getChildAt(0).getTop() to do this. I save the value of getChildAt(0).getTop() on first draw and compare to getChildAt(0).getTop() on subsequent draws .

However, this seems hacky and seems to sometimes give me incorrect results.

Any better ideas?

user1435114
  • 193
  • 1
  • 11

4 Answers4

1

Try using the onScrollListener

setOnScrollListener(this);

@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

    if(firstVisibleItem == 0){
        //do stuff here
    }

}
JackMahoney
  • 3,423
  • 7
  • 32
  • 50
  • If the first item is visible it doesn't mean GridView is scrolled to top. –  May 19 '15 at 07:31
0

The getChildAt(0) returns you the first visible item of the GridView and I guess that it's not what you want.

If you use yourGridView.getFirstVisiblePosition() method it will return the first visible position your data adapter, and that is what you want.

yugidroid
  • 6,640
  • 2
  • 30
  • 45
  • Hmm. I don't see how yourGridView.getFirstVisiblePosition() gives me what I want, unless I'm misunderstanding "visible." If the second row is the first row visible, I want the overall method I'm trying to write -- isGridScrolledToTop() -- to return false. It should return false in this case the grid isn't scrolled to its top. (It's scrolled to the second row.) – user1435114 Jul 16 '12 at 14:54
  • this isn't very accurate i find. – JMRboosties Jan 30 '14 at 18:56
0

Hope this can help, it works for me, good luck.

yourGridView.setOnScrollListener(new OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { if(SCROLL_STATE_IDLE == scrollState) { View view = view.getChildAt(0); if(view != null) { float y = view.getY(); Log.d("Tag", "first view Y is " + y); if(y == 0) { // do what you want } } } }

tomisyourname
  • 91
  • 1
  • 11
0

This's my answer:

mLayoutManager = new GridLayoutManager(getActivity(), 2);
mListRV= (RecyclerView).findViewById(R.id.list_rv);
mListRV.setLayoutManager(mLayoutManager);

mListRV.setOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                    if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                        View v = mLayoutManager.getChildAt(0);
                        int offsetTop = v.getTop();
                        int offsetBottom = v.getBottom();
                        int height = (offsetBottom - offsetTop);
                        if(offsetTop >= -height/2) {
                            mListRV.smoothScrollBy(0, offsetTop);
                        } else {
                            mListRV.smoothScrollBy(0, height + offsetTop);
                        }
                    } 
                }
            });
TVT. Jake
  • 279
  • 2
  • 7