方式一
/**
* @param headLayout
* 头部布局
* @param imageview
* 标题
*/
Toolbar toolbar;
View headView;
public void setTitleAndHead(Toolbar toolbar, View headView) {
this.toolbar = toolbar;
this.headView = headView;
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
if (headView != null && toolbar != null) {
float headHeight = headView.getMeasuredHeight()
- toolbar.getMeasuredHeight();
int alpha = (int) (((float) t / headHeight) * 255);
if (alpha >= 255)
alpha = 255;
if (alpha <= 0)
alpha = 0;
toolbar.getBackground().mutate().setAlpha(alpha);
}
super.onScrollChanged(l, t, oldl, oldt);
}
方式二
/**
* 改变Toolbar的透明度
*/
private void changeToolbarAlpha() {
int scrollY = scrollView.getScrollY();
//快速下拉会引起瞬间scrollY < 0
if (scrollY < 0) {
toolbar.getBackground().mutate().setAlpha(0);
return;
}
//计算当前的透明度
float radio = Math.min(1, scrollY / (ivImg.getHeight() - toolbar.getHeight() * 1f));
//设置透明度
toolbar.getBackground().mutate().setAlpha((int) (radio * 0xFF));
}
方式三
@Override
public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
int abs_y = Math.abs(scrollY);
//如果在变化的范围内
if ((scrollLength - abs_y) > 0) {
// 算法:开始值 +(结束值 - 开始值)* 进度
IntEvaluator evaluator = new IntEvaluator();
// 总数-变动的值/总数 ( 变动的值范围:0~总数 )
// 结果比例:1 ~ 0
float percent = (float) (scrollLength - abs_y) / scrollLength;
//标题栏透明度
int evaluate = evaluator.evaluate(percent, 255, 0);
rv_bar.getBackground().mutate().setAlpha(evaluate);
}else {
rv_bar.getBackground().mutate().setAlpha(255);
}