我们先来看看效果
继承RecyclerView.OnScrollListener重写onScrolled方法,同时定义两个抽象方法供我们处理隐藏和显示事件
public abstract class HidingScrollListener extends RecyclerView.OnScrollListener {
private static final int HIDE_THRESHOLD = 20;
private int scrolledDistance = 0;
private boolean controlsVisible = true;
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (scrolledDistance > HIDE_THRESHOLD && controlsVisible) {
onHide();
controlsVisible = false;
scrolledDistance = 0;
}
else if (scrolledDistance < -HIDE_THRESHOLD && !controlsVisible) {
onShow();
controlsVisible = true;
scrolledDistance = 0;
}
if ((controlsVisible && dy > 0) || (!controlsVisible && dy < 0)) {
scrolledDistance += dy;
}
}
public abstract void onHide();
public abstract void onShow();
}
事件的处理
recyclerView.addOnScrollListener(new HidingScrollListener() {
@Override
public void onHide() {
Resources resources = MainActivity.this.getResources();
DisplayMetrics dm = resources.getDisplayMetrics();
float density = dm.density;
int width = dm.widthPixels;
int height = dm.heightPixels;
fab.animate()
.translationY(height - fab.getHeight())
.setInterpolator(new AccelerateInterpolator(2))
.start();
buttom.animate()
.translationY(height - buttom.getHeight())
.setInterpolator(new AccelerateInterpolator(2))
.setDuration(800)
.start();
top.animate()
.translationY(-height)
.setDuration(800)
.setInterpolator(new AccelerateInterpolator(2))
.start();
}
@Override
public void onShow() {
fab.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2)).start();
buttom.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2)).setDuration(800).start();
top.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2)).setDuration(800).start();
}
});
布局文件
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:clipToPadding="false"
android:paddingTop="?attr/actionBarSize"
android:layout_height="match_parent"/>
<LinearLayout
android:id="@+id/top"
android:layout_width="match_parent"
android:layout_height="52dp"
android:background="#f00"
android:orientation="vertical">
</LinearLayout>
<LinearLayout
android:id="@+id/buttom"
android:layout_width="match_parent"
android:layout_height="52dp"
android:layout_gravity="bottom"
android:background="#f00"
android:orientation="vertical">
</LinearLayout>
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
android:layout_marginBottom="40dp"
app:borderWidth="0dp"
/>
</FrameLayout>