类似这种效果,想必大家都看过,如某宝的商品详情页,小米商城首页等。。。
我们这里是自定义一个ScrollView去监听控件的滑动,然后不断去改变标题栏的透明度。
/**
* Created by zwr on 2017/3/11.
* 自定义的ScrollView
*/
```
publicclassChangeAlphaScrollViewextendsScrollView {
privateOnScrollChangedListenermOnScrollChangedListener;
publicChangeAlphaScrollView(Context context) {
super(context);
}
```
publicChangeAlphaScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
publicChangeAlphaScrollView(Context context, AttributeSet attrs,intdefStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protectedvoidonScrollChanged(intl,intt,intoldl,intoldt) {
super.onScrollChanged(l, t, oldl, oldt);
if(mOnScrollChangedListener!=null) {
mOnScrollChangedListener.onScrollChanged(this, l, t, oldl, oldt);
}
}
publicvoidsetOnScrollChangedListener(OnScrollChangedListener listener) {
mOnScrollChangedListener= listener;
}
publicinterfaceOnScrollChangedListener {
void onScrollChanged(ScrollView who,intl,intt,intoldl,intoldt);
}
}
**
* Created by zwr on 2017/3/11.
mianactivity去实现接口
*/
publicclassMainActivityextendsAppCompatActivityimplementsChangeAlphaScrollView.OnScrollChangedListener {
privateImageViewimageView;
privateToolbartoolBar;
privatefloatheaderHeight;//顶部高度
privatefloatminHeight;//顶部最低高度,即Bar的高度
privateChangeAlphaScrollViewscrollView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView= (ImageView) findViewById(R.id.imageView);
scrollView= (ChangeAlphaScrollView) findViewById(R.id.myScrollView);
toolBar= (Toolbar) findViewById(R.id.tool_bar_home);
scrollView.setOnScrollChangedListener(this);
getMeasure();
}
@Override
public void onScrollChanged(ScrollView who,intl,intt,intoldl,intoldt) {
//得到y轴的偏移量
floatscrollY= who.getScrollY();
//变化率
floatheaderBarOffsetY=headerHeight-minHeight;
floatoffset=1- Math.max((headerBarOffsetY-scrollY) /headerBarOffsetY,0f);
//Toolbar背景色透明度
toolBar.setBackgroundColor(Color.argb((int) (offset*255),255,64,129));//颜色的RGB值
}
//调用此方法重新测量得到控件高度
private void getMeasure() {
intw= View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
inth= View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
imageView.measure(w,h);
headerHeight=imageView.getMeasuredHeight();
toolBar.measure(w,h);
minHeight=toolBar.getMeasuredHeight();
}
}
```
注:若有错误欢迎指正
网友评论