image
上图可以看出ScrollView滑动效果: 由顶部向下滑动是 scrollView 顶部有透明色逐渐变成黑色..向上滑动时,由黑色变成为透明色;
主要实现过程:监听ScrollView的滚动事件,当ScrollView 从头开始滑动到一定距离,顶部的View 颜色发生渐变,有不透明到透明..
/**
Created by ${chenglin} on 2018/5/30.
使用方法
在Activity 中 findviewbyid
设置 mGradientSrcollView.init(); 方法
*/
public class GradientSrcollViewextends ScrollView{
private int fading_Height =600; // 当ScrollView滑动到什么位置时渐变消失(根据需要进行调整)
private Drawabledrawable; // 顶部渐变布局需设置的Drawable
//因为颜色的色值为 0-255 start-end 设置颜色的透明度
private int START_ALPHA =0;//scrollview滑动开始位置
private int END_ALPHA =255 ;//scrollview滑动结束位置
public GradientSrcollView(Context context) {
super(context);
}
public GradientSrcollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public GradientSrcollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
//view 顶部要渐变的颜色 控件View
public void init(int fadingHeight,int color,View view){
fading_Height = fadingHeight;
drawable = getResources().getDrawable(color);
drawable.setAlpha(START_ALPHA);
view.setBackgroundDrawable(drawable);
}
@Override
protected void onScrollChanged(int l, int scrollY, int oldl, int oldt) {
super.onScrollChanged(l, scrollY, oldl, oldt);
if (scrollY >fading_Height) {
scrollY =fading_Height; // 当滑动到指定位置之后设置颜色为纯色,之前的话要渐变---实现下面的公式即可
// rlTop.setBackgroundColor(getResources().getColor(R.color.colorAccent));
}else if (scrollY <0) {
scrollY =0;
}else {
// rlTop.setBackgroundColor(getResources().getColor(R.color.colorTranslate));
}
drawable.setAlpha(scrollY * (END_ALPHA -START_ALPHA) /fading_Height
+START_ALPHA);
}