Search code examples
androidandroid-recyclerviewmaterial-designandroid-collapsingtoolbarlayoutandroid-appbarlayout

Find first completely visible element in recyclerview


I have a layout in which it has parallax effect. So this are the elements in it -

  1. AppBarLayout
  2. CollapsingToolbarLayout inside AppBarLayout
  3. Toolbar inside CollapsingToolbarLayout
  4. RecyclerView

All this views are within CoordinatorLayout. Now I require to find out what is the first completely visible item of RecyclerView. Normally I used following logic to get it -

int firstVisibleItem = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstCompletelyVisibleItemPosition();

But here I am getting lots of 1 when even 0th position is not completely visible.


Solution

  • I found it myself. As I am using AppBarLayout, I need to check it out whether particular view is available on screen at that particular scroll or not.

    I did is:

    @Override
        public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
    
            View v = recyclerView.getLayoutManager().getChildAt(1);
            int offset = 0;
            if (v != null) {
                offset = v.getTop();
            }
    
            if ((verticalOffset * -1) >= offset) {
                layoutBuy.setVisibility(View.GONE);
            } else {
                layoutBuy.setVisibility(View.VISIBLE);
            }
        }
    

    I used recyclerView.getLayoutManager().getChildAt(1); because I wanted to work around with that particular position which is 1.

    Since, vertical offset becomes minus values while scrolling I multiplied it by -1. Then just checked whether offset and top of the view which I am looking for is same or not.

    Thus while using parallax effect in a screen and at that same time one needs to check which view is visible in RecyclerView, needs the logic as mentioned above.