Android Hide Floating Action Button While RecyclerView Scroll Example

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

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

compile ‘com.android.support:design:26.+’

compile ‘com.android.support:recyclerview-v7:26.+’

android hide floating button while recyclerview scroll example

1. Floating Action Button Attributes Settings.

Below is this example’s main layout xml file. It contains android floating action button attributes settings.

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>

FloatActionButton Attributes.

Please note the bold red lines in above layout xml file.

  1. android:src : The icon of this button, google recommend 24dp size icon.
  2. app:layout_behavior : This is the custom behavior class which process hide or show floating action button action indeed. It must extends 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 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 : Setting 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, default value is 12dp.
  10. app:elevation : Normal shadow size, default value is 6dp.

2. Floating Action Button Example Java Files.

This example contains one CoordinatorLayout which includes a RecyclerView and FloatingActionButton.

READ :   Android RecyclerView Example

You must set the FloatingActionButton just under the CoordinatorLayout. Otherwise the effect will disappear.

andorid floating action button example file structure

2.1 Main Activity.

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.

This is the java class that is used in layout xml file as FloatingActionButton’s app:layout_behavior attribute value.

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;

/**
 * Created by Jerry on 3/12/2018.
 */

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.

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;

/**
 * Created by Jerry on 3/12/2018.
 */

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.

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;

/**
 * Created by Jerry on 3/12/2018.
 */

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.

RecyclerViewItem.java

package com.dev2qa.example.material_design.floatingactionbutton;

/**
 * Created by Jerry on 3/12/2018.
 */

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.

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
(Visited 457 times, 3 visits today)

Leave a Reply

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.