Christopher
Christopher

Reputation: 149

"Back to top" button to be displayed only after scrolling

I have a RecyclerView that display pictures, and have put a FloatingActionButton to let my user go back to the top of the view like such:

// On FAB click, scroll back to the top of the layout
private void handleUp() {
    FloatingActionButton FAB = (FloatingActionButton) view.findViewById(R.id.upFAB);
    FAB.setOnClickListener(view1 -> {
        if (recyclerView != null) {
            recyclerView.smoothScrollToPosition(0); 
        }
    });
}

With the following view:

<android.support.design.widget.FloatingActionButton
    app:fabSize="mini"
    android:id="@+id/upFAB"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@mipmap/up_icon"
    android:layout_gravity="bottom|center"
    android:layout_marginBottom="60dp" />

It looks like this.

As you can see the button is displayed all the time, how may I only display it when the user scrolls for a certain amount in the RecyclerView?

Upvotes: 3

Views: 3105

Answers (2)

Vishal Chhodwani
Vishal Chhodwani

Reputation: 2577

I just did it through ListView.

Here is the example using ListView instead of RecycleView.

Try this, Hope it will help.

listView.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {

        }

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

            if(firstVisibleItem > 2)
            {
                upFAB.setVisibility(View.VISIBLE);
            }
            else
            {
                upFAB.setVisibility(View.GONE);
            }
        }
    });

Upvotes: 0

Yassine BELDI
Yassine BELDI

Reputation: 572

try this way and tell me , i didn't try it

 mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition();

            if (firstVisibleItem > 1) {
                //Show FAB
            }
            else{
               //Hide FAB
            }
        }
    });

Upvotes: 4

Related Questions