Android Hide Floating Action Button While RecyclerView Scroll Example

This example will show you how to make an android floating action button hide and show when the user scrolls a recycler view.

android.support.design.widget.FloatingActionButton class is used to implement the floating action button. It is supported by the android material design support library, so before starting, make sure you have added the below dependence library in your android project build.gradle file.

compile 'com.android.support:design:26.+'
compile 'com.android.support:recyclerview-v7:26.+'

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/ejTrSiAhR84

1. Floating Action Button Attributes Settings.

  1. Below is this example’s main layout XML file. It contains android floating action button attributes settings.
  2. activity_floating_action_button.xml
    <android.support.design.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <android.support.v7.widget.RecyclerView
            android:id="@+id/floating_action_button_recycler_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    
        <android.support.design.widget.FloatingActionButton
            android:id="@+id/floating_action_button"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_margin="10dp"
            android:scaleType="center"
            android:src="@drawable/android_floating_action_button_icon"
            app:layout_behavior="com.dev2qa.example.material_design.floatingactionbutton.FloatingActionButtonScrollBehavior"
            app:layout_anchor="@id/floating_action_button_recycler_view"
            app:layout_anchorGravity="bottom|end"
            app:borderWidth="1dp"
            app:elevation="10dp" />
    
    </android.support.design.widget.CoordinatorLayout>

1.1 FloatActionButton Attributes.

  1. android:src: The icon of this button, google recommends a 24dp size icon.
  2. app:layout_behavior: This is the custom behavior class that processes hide or shows floating action button action indeed. It must extend FloatingActionButton.Behavior.
  3. app:layout_anchor: The anchor view’s id of the floating action button.
  4. app:layout_anchorGravity: The position of the floating action button relative to the anchor view object.
  5. app:backgroundTint: Button default color.
  6. app:borderWidth: The border width of the button. If you find the button change to square or do not have shadow in android os version 4 or 5  then set it to 0.
  7. app:fabSize: Set the floating action button size style, normal is 56dp, mini is 40dp.
  8. app:rippleColor: Button color when being clicked. Default value is theme’s colorControlHighlight value.
  9. app:pressedTranslationZ: The shadow size when the button is clicked, the default value is 12dp.
  10. app:elevation: Normal shadow size, the default value is 6dp.

2. Floating Action Button Example Java Files.

  1. This example contains one CoordinatorLayout which includes a RecyclerView and a FloatingActionButton.
  2. You must set the FloatingActionButton just under the CoordinatorLayout. Otherwise, the effect will disappear.
    D:\WORK\DEV2QA.COM-EXAMPLE-CODE\ANDROIDEXAMPLEPROJECT\EXAMPLE\APP\SRC\MAIN\JAVA\COM\DEV2QA\EXAMPLE\MATERIAL_DESIGN\FLOATINGACTIONBUTTON
        FloatingActionButtonActivity.java
        FloatingActionButtonScrollBehavior.java
        RecyclerViewDataAdapter.java
        RecyclerViewItem.java
        RecyclerViewItemHolder.java

2.1 Main Activity.

  1. FloatingActionButtonActivity.java
    package com.dev2qa.example.material_design.floatingactionbutton;
    
    import android.os.Bundle;
    import android.support.design.widget.FloatingActionButton;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.DividerItemDecoration;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.view.View;
    import android.widget.Toast;
    
    import com.dev2qa.example.R;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class FloatingActionButtonActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_floating_action_button);
    
            setTitle("dev2qa.com - Floating Action Bar Example.");
    
            final FloatingActionButton floatingActionButton = (FloatingActionButton)findViewById(R.id.floating_action_button);
            floatingActionButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(getApplicationContext(),"You click the floating action button.", Toast.LENGTH_LONG).show();
                }
            });
    
            initializeRecyclerView();
        }
    
    
        /* Initialize recyclerview object and populate it as a list view with data. */
        private void initializeRecyclerView()
        {
            RecyclerView recyclerView = (RecyclerView)findViewById(R.id.floating_action_button_recycler_view);
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
            linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            recyclerView.setLayoutManager(linearLayoutManager);
    
            // Create recyclerview adapter and set data list.
            List<RecyclerViewItem> recyclerViewItemList = getRecyclerViewItemDtoList();
            RecyclerViewDataAdapter recyclerViewDataAdapter = new RecyclerViewDataAdapter(recyclerViewItemList);
            recyclerView.setAdapter(recyclerViewDataAdapter);
    
            // Use default linear layout item divider.
            DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(getApplicationContext(), LinearLayoutManager.VERTICAL);
            recyclerView.addItemDecoration(dividerItemDecoration);
        }
    
        /* Create and return a list of RecyclerViewItem. */
        private List<RecyclerViewItem> getRecyclerViewItemDtoList()
        {
            List<RecyclerViewItem> ret = new ArrayList<RecyclerViewItem>();
    
            for(int i=0;i<20;i++)
            {
                RecyclerViewItem itemDto = new RecyclerViewItem();
    
                if(i%2 == 0) {
                    itemDto.setTitle("Smile Face " + i);
                }else
                {
                    itemDto.setTitle("Red Apple " + i);
                }
    
                ret.add(itemDto);
            }
    
            return ret;
        }
    }

2.2 Floating Action Button Behavior Class.

  1. This is the java class that is used in the layout XML file as FloatingActionButton‘s app:layout_behavior attribute value.
  2. FloatingActionButtonScrollBehavior.java
    package com.dev2qa.example.material_design.floatingactionbutton;
    
    import android.content.Context;
    import android.support.design.widget.CoordinatorLayout;
    import android.support.design.widget.FloatingActionButton;
    import android.support.v4.view.ViewCompat;
    import android.util.AttributeSet;
    import android.view.View;
    
    
    public class FloatingActionButtonScrollBehavior extends FloatingActionButton.Behavior {
    
        /* Must provide this constructer method, otherwise app will throw Could not inflate Behavior subclass error message. */
        public FloatingActionButtonScrollBehavior(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        @Override
        public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout, FloatingActionButton child, View directTargetChild, View target, int nestedScrollAxes) {
            boolean ret = false;
            if(nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL)
            {
                ret = true;
            }else
            {
                ret = super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, nestedScrollAxes);
            }
    
            return ret;
        }
    
        @Override
        public void onNestedScroll(CoordinatorLayout coordinatorLayout, FloatingActionButton child, View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) {
            super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed);
                 /* If RecyclerView scroll action consumed vertical pixels bigger than 0, means scroll down. */
            if (dyConsumed > 0) {
                if(child.getVisibility() == View.VISIBLE) {
                    child.hide(new FloatingActionButton.OnVisibilityChangedListener() {
                        @Override
                        public void onHidden(FloatingActionButton floatingActionButton) {
                            super.onHidden(floatingActionButton);
                            floatingActionButton.setVisibility(View.INVISIBLE);
                        }
                    });
                }
            }
            // Means recyclerview scroll up.
            else if (dyConsumed < 0 && child.getVisibility() != View.VISIBLE) {
                child.show();
            }
        }
    }

2.3 RecyclerView Data Adapter.

  1. RecyclerViewDataAdapter.java
    package com.dev2qa.example.material_design.floatingactionbutton;
    
    import android.support.v7.widget.RecyclerView;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    
    import com.dev2qa.example.R;
    
    import java.util.List;
    
    public class RecyclerViewDataAdapter extends RecyclerView.Adapter<RecyclerViewItemHolder> {
    
        private List<RecyclerViewItem> itemList;
    
        public RecyclerViewDataAdapter(List<RecyclerViewItem> itemList) {
            this.itemList = itemList;
        }
    
        @Override
        public RecyclerViewItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            // Get LayoutInflater object.
            LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
            // Inflate the RecyclerView item layout xml.
            View itemView = layoutInflater.inflate(R.layout.activity_floating_action_button_recycler_view_item, parent, false);
    
            // Create and return our custom RecyclerViewItemHolder object.
            RecyclerViewItemHolder ret = new RecyclerViewItemHolder(itemView);
            return ret;
        }
    
        @Override
        public void onBindViewHolder(RecyclerViewItemHolder holder, int position) {
            // Get item dto in list.
            RecyclerViewItem item = itemList.get(position);
            // Set item text.
            holder.getItemText().setText(item.getTitle());
        }
    
        @Override
        public int getItemCount() {
            int ret = 0;
            if(this.itemList!=null)
            {
                ret = this.itemList.size();
            }
            return ret;
        }
    }

2.4 RecyclerView Holder.

  1. RecyclerViewItemHolder.java
    package com.dev2qa.example.material_design.floatingactionbutton;
    
    import android.support.v7.widget.RecyclerView;
    import android.view.View;
    import android.widget.TextView;
    
    import com.dev2qa.example.R;
    public class RecyclerViewItemHolder extends RecyclerView.ViewHolder {
    
        // Cache the RecyclerView item text object.
        private TextView itemText = null;
    
        public RecyclerViewItemHolder(View itemView) {
            super(itemView);
            if(itemView!=null) {
                itemText = (TextView)itemView.findViewById(R.id.floating_action_button_recycler_view_text);
            }
        }
    
        public TextView getItemText() {
            return itemText;
        }
    }

2.5 RecyclerView Item.

  1. RecyclerViewItem.java
    package com.dev2qa.example.material_design.floatingactionbutton;
    
    public class RecyclerViewItem {
        private String title = "";
    
        public String getTitle() {
            return title;
        }
    
        public void setTitle(String title) {
            this.title = title;
        }
    }

2.6 RecyclerView Item XML Definition File.

  1. activity_floating_action_button_recycler_view_item.xml
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp">
    
        <TextView
            android:id="@+id/floating_action_button_recycler_view_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="20dp"/>
    
    </LinearLayout>

Reference

  1. Android RecyclerView Example

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.