Issue
Is it possible to check if the first or second item of the RecyclerView
is visible on the screen of the user?
For example when the user scrolls down:
if (first item not visible to user) {
// do something
}
else if ( first item is visible){
// do something
}
What I currently do is I add a listener to my recycler so that when the user scrolls down, it will do something and scroll up.
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (dy > 0) {
mAccountLayout.setVisibility(View.GONE);
mDateLayout.setVisibility(View.GONE);
Log.d("SCROLLINGDOWN","SCROLL");
} else {
mAccountLayout.setVisibility(View.VISIBLE);
mDateLayout.setVisibility(View.VISIBLE);
Log.d("SCROLLINGUP","SCROLL");
}
}
});
But what I need is to check if the first item is visible or not.
Solution
You can find some helper methods in RecyclerView.LayoutManager
, for example, if you use a LinearLayoutManager
, check these methods:
int findFirstCompletelyVisibleItemPosition() // Returns the adapter position of the first fully visible view.
int findFirstVisibleItemPosition() // Returns the adapter position of the first visible view.
int findLastCompletelyVisibleItemPosition() // Returns the adapter position of the last fully visible view.
int findLastVisibleItemPosition() // Returns the adapter position of the last visible view.
See the full docs here.
In your code:
recyclerView.setAdapter(adapter);
final LinearLayoutManager layoutManager = new LinearLayoutManager(context);
recyclerView.setLayoutManager(layoutManager);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (layoutManager.findFirstVisibleItemPosition() > 0) {
mAccountLayout.setVisibility(View.GONE);
mDateLayout.setVisibility(View.GONE);
Log.d("SCROLLINGDOWN","SCROLL");
} else {
mAccountLayout.setVisibility(View.VISIBLE);
mDateLayout.setVisibility(View.VISIBLE);
Log.d("SCROLLINGUP","SCROLL");
}
}
});
Answered By - Hong Duan