Reputation: 3572
I'm trying to show fab only when I scroll to a particular element of recyclerView. This is my layout which I thought out all the stuff for shorting purpose. So what I want it to show fab on 2,3,3... items and do not show it on zero and first items of my RecyclerView.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:id="@+id/appBarLayout">
<android.support.v7.widget.Toolbar
android:id="@+id/details_toolbar"/>
<include layout="@layout/divider" />
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.RecyclerView
android:id="@+id/topic_content_recycler"/>
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"/>
</android.support.design.widget.CoordinatorLayout>
What I found is to hide fab on scrolling, which looks like this:
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener(){
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy){
if (dy > 0)
fabAddNew.hide();
else if (dy < 0)
fabAddNew.show();
}
});
I want well written solution. (I assume there is one, provided by google, but I can't fund it) Thank you.
Upvotes: 1
Views: 356
Reputation: 621
add the RecyclerView.OnScrollListener
and use the onScrollStateChanged(RecyclerView recyclerView, int newState)
callback which gives you the newState, you should use SCROLL_STATE_IDLE to fetch its position.
which means position changed and scrolling stopped now you can check which item is visible with the help of this
recyclerView.getLayoutManager().findFirstVisibleItemPosition();
now you can use the following code and change it accordingly
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (dy > 0) {
// Scrolling up
} else {
// Scrolling down
}
}
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == AbsListView.OnScrollListener. SCROLL_STATE_IDLE) {
//you can change the position according to your need
if(recyclerView.getLayoutManager().findFirstVisibleItemPosition()<2)
{
fabAddNew.hide();
}
else{
fabAddNew.show();
}
}
}
});
you can read the documentation here for more detail
Upvotes: 3