binding.scrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
@Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
Log.e("caixin","滑动了----------"+scrollY);
if (scrollY <= 0) {
// activityBindDeviceBinding.appBar.binding.appBarBg.setBackgroundColor(0xF200F7);
activityBindDeviceBinding.appBar.binding.title.setAlpha((float) 0);
Log.e("caixin","滑动了yyyy----------隐藏了");
} else if (scrollY > 0 && scrollY <= 150) {
float scale = (float) scrollY / 150;
float alpha = (255 * scale);
Log.e("caixin","滑动了yyyy----------"+alpha);
// layout背景透明
// activityBindDeviceBinding.appBar.setBackgroundColor(0xF200F7);
activityBindDeviceBinding.appBar.binding.title.setAlpha((float) scale);
} else {
// activityBindDeviceBinding.appBar.setBackgroundColor(0xF200F7);
Log.e("caixin","滑动了yyyy----------显示了");
activityBindDeviceBinding.appBar.binding.title.setAlpha(1);
}
}
});
标题栏渐变重点是[监听]Scrollview的滚动距离,所以重写了onScrollChanged方法监听滚动距离:
public class ChangeColorScrollview extends ScrollView{
public ChangeColorScrollview(Context context) {
super(context);
}
public ChangeColorScrollview(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ChangeColorScrollview(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
private ScrollViewListener scrollViewListener = null;
public interface ScrollViewListener {
void onScrollChanged(ChangeColorScrollview scrollView, int x, int y,
int oldx, int oldy);
}
public void setScrollViewListener(ScrollViewListener scrollViewListener) {
this.scrollViewListener = scrollViewListener;
}
@Override
protected void onScrollChanged(int x, int y, int oldx, int oldy) {
super.onScrollChanged(x, y, oldx, oldy);
if (scrollViewListener != null) {
scrollViewListener.onScrollChanged(this, x, y, oldx, oldy);
}
}
}
使用方法也很简单,直接加入如下代码:
scrollView.setScrollViewListener(new ChangeColorScrollview.ScrollViewListener() {
@Override
public void onScrollChanged(ChangeColorScrollview changeColorScrollview, int x, int y, int oldx, int oldy) {
//改变标题栏颜色 y为欢动距离
if (y <= 0) {
titleLinearLayout.setBackgroundColor(Color.argb((int) 0, 227, 29, 26));
titleLinearLayout.setAlpha((float) 0.7);
} else if (y > 0 && y <= height) {
float scale = (float) y / height;
float alpha = (255 * scale);
// layout背景透明
titleLinearLayout.setBackgroundColor(Color.argb((int) alpha, 227, 29, 26));
} else {
titleLinearLayout.setBackgroundColor(Color.argb((int) 255, 227, 29, 26));
titleLinearLayout.setAlpha(1);
}
}
});
也直接可做回到顶部功能。