项目中需要做一个类似手机QQ中查看个人资料,当向上滚动页面时候,头部的底色会根据滚动的距离渐变改变颜色。
看考了这个https://github.com/AChep/Header2ActionBar 库,但是这个库用了actionbar,而且在4.0~4.1的系统都无效。想必要做一个可以上下兼容的效果。
原理比较简单,重写ScrollView,添加onScrollChangeLisener,再根据滚动去调整颜色值。
关键代码:
scrollview.setOnScrollChangedListener(newOnScrollChangedListener() { @Override publicvoid onScrollChanged(ScrollView who, int l, int t, int oldl, intoldt) { //defineit for scroll height intlHeight = 400; if(t<=lHeight){ intprogress = (int)(new Float(t)/new Float(lHeight)*255); layoutHead.getBackground().setAlpha(progress); }else{ layoutHead.getBackground().setAlpha(255); } } });
例子已经开源到https://github.com/arjinmc/ScrollViewHead
原文地址:http://blog.csdn.net/arjinmc/article/details/44195967