Appbarlayou随rv滚动达成相应效果
appbarlayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (Math.abs(verticalOffset * 1.0f) / appBarLayout.getTotalScrollRange() == 1) {
img.setImageResource(R.mipmap.home_messa_r);//滑动图片渐变
} else {
img.setImageResource(R.mipmap.home_messa);
}
//滑动toolbar渐变
toolbar.setBackgroundColor(changeAlpha(getResources().getColor(R.color.colorPrimaryDark), Math.abs(verticalOffset * 1.0f) / appBarLayout.getTotalScrollRange()));
}
});
/**
* 根据百分比改变颜色透明度
*/
public int changeAlpha(int color, float fraction) {
int red = Color.red(color);
int green = Color.green(color);
int blue = Color.blue(color);
int alpha = (int) (Color.alpha(color) * fraction);
return Color.argb(alpha, red, green, blue);
}
一般 配合recycleview使用
recycleview.addOnScrollListener(new RecyclerView.OnScrollListener() {
int scrollY = 0;
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
//未滚动
if (!recyclerView.canScrollVertically(-1) && scrollY < -10) {
//do somthing
appbarlayout.setExpanded(true, true);//通知AppBarLayout伸展
scrollY = 0;
}
}
//判断慢速滚动:当滚动到顶部时靠手指拖动后的惯性让RecyclerView处于Fling状态时的速度大于5时,让AppBarLayout展开
if (newState == RecyclerView.SCROLL_STATE_SETTLING) {
//正在滚动中,惯性滚动
if (!recyclerView.canScrollVertically(-1) && scrollY < -5) {
//do somthing
appbarlayout.setExpanded(true, true);
scrollY = 0;
}
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
scrollY = dy;
}
});