参考自:http://blog.csdn.net/smart_yc/article/details/52575651
效果:
核心代码:
//headview为头布局;llSearch为搜索栏
recyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
//滑动的距离
mDistanceY += dy;
//上方图片的高度
int headHeight = headView.getHeight();
if (mDistanceY < headHeight) {
//滑动距离小于上方图片的1/2时,设置白色搜索按钮,透明度从0-255
if (mDistanceY < headHeight / 2) {
imgSearch.setImageResource(R.mipmap.search_white);
float scale = (float) mDistanceY / (headHeight / 2);
float alpha = scale * 255;
llSearch.getBackground().setAlpha((int) alpha);
} else {//滑动距离大于上方图片的1/2并小于上方图片时,设置黑色搜索按钮,透明度从0-255
imgSearch.setImageResource(R.mipmap.search_black);
float scale = (float) (mDistanceY - headHeight / 2) / (headHeight / 2);
float alpha = scale * 255;
llSearch.getBackground().setAlpha((int) alpha);
}
} else {
//当快速往下滑时,llSearch最后设置的alpha不约等于255,测试的为132,所以要再设置
llSearch.getBackground().setAlpha(255);
}
}
});