复写RecyclerView.OnScrollListener监听事件,使RecyclerView具有滑动显示/隐藏功能
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
/**
* Created by pc on 2016/7/1.
*/
public abstract class HidingScrollBottomListener extends RecyclerView.OnScrollListener {
private static final int HIDE_THRESHOLD = 20;//滑动隐藏的阈值
private int mScrolledDistance = 0;//滑动距离
private boolean mControlsVisible = true;//控件的显示状态
/**
* 向下滑动隐藏控件, 向上滑动显示控件
* dy, 向下滑动为正值, 向上滑动为负值
*/
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int firstVisibleItem = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
if (firstVisibleItem == 0) {//如果已经滑动到最顶端
if(!mControlsVisible) {
onShow();
mControlsVisible = true;
}
} else {//当前Item不是第一条
if (mScrolledDistance > HIDE_THRESHOLD && mControlsVisible) {//向下滑动
onHide();
mControlsVisible = false;
mScrolledDistance = 0;
} else if (mScrolledDistance < -HIDE_THRESHOLD && !mControlsVisible) {//向上滑动
onShow();
mControlsVisible = true;
mScrolledDistance = 0;
}
}
if((mControlsVisible && dy>0) || (!mControlsVisible && dy<0)) {
mScrolledDistance += dy;
}
}
public abstract void onHide();//在onHide()方法里面实现控件隐藏功能
public abstract void onShow();//在onShow()方法里面实现控件显示功能
}
使用自定义滑动监听事件HidingScrollBottomListener
recyclerView.addOnScrollListener(new HidingScrollBottomListener() {
@Override
public void onHide() {
hideViews();
}
@Override
public void onShow() {
showViews();
}
});
private void hideViews() {
FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) fab.getLayoutParams();//获取控件的布局参数
int fabBottomMargin = lp.bottomMargin;//与父控件的底部间隔
fab.animate()//动画
.translationY(fab.getHeight() + fabBottomMargin)//Y轴上的变换高度
.setInterpolator(new AccelerateInterpolator(2))//播放速度
.start();
}
private void showViews() {
fab.animate()
.translationY(0)
.setInterpolator(new DecelerateInterpolator(2))
.start();
}