ScrollView 自定义滑动监听
public class MyScrollView extends ScrollView {
private OnScrollistener onScrollistener;
public OnScrollistener getOnScrollistener() {
return onScrollistener;
}
public void setOnScrollistener(OnScrollistener onScrollistener) {
this.onScrollistener = onScrollistener;
}
public MyScrollView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public MyScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyScrollView(Context context) {
super(context);
}
public interface OnScrollistener {
void onScroll(int startY, int endY);
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
onScrollistener.onScroll(oldt, t);
super.onScrollChanged(l, t, oldl, oldt);
}
}
调用
mLevelPrivilege.setOnScrollistener(new MyScrollView.OnScrollistener() {
@Override
public void onScroll(int startY, int endY) {
//根据scrollview滑动更改标题栏透明度
dynamicChangeAphla(startY, endY);
}
});
透明度设置
/**
* 根据内容窗体的移动改变标题栏背景透明度
*
* @param startY scrollview开始滑动的y坐标(相对值)
* @param endY scrollview结束滑动的y坐标(相对值)
*/
private void dynamicChangeAphla(int startY, int endY) {
//获取标题高度
int titleHeight = llayoutLevelTitle.getMeasuredHeight();
//获取背景高度
int backHeight = rlayoutLevelTitle.getMeasuredHeight();
//获取控件的绝对位置坐标
int[] location = new int[2];
rlayoutLevelTitle.getLocationInWindow(location);
//从屏幕顶部到控件顶部的坐标位置Y
int currentY = location[1];
//表示回到原位(滑动到顶部)
if (currentY >= 0) {
llayoutLevelTitle.getBackground().mutate().setAlpha(0);
}
DevUtil.e("zpan","=titleHeight=" + titleHeight + "=backHeight=" + backHeight + "=currentY="+currentY);
//颜色透明度改变
if (currentY < titleHeight && currentY >= - (backHeight - titleHeight)) {
//计算出滚动过程中改变的透明值
double y = Math.abs(currentY) * 1.0;
double height = (backHeight - titleHeight) * 1.0;
int changeValue = (int) (y / height * 255);
DevUtil.e("zpan", "changeValue=" + changeValue);
//判断是向上还是向下
if (endY > startY) {//向上;透明度值增加,实际透明度减小
llayoutLevelTitle.getBackground().mutate().setAlpha(changeValue);
} else if (endY < startY) {//向下;透明度值减小,实际透明度增加
llayoutLevelTitle.getBackground().mutate().setAlpha(changeValue);
}
}
//红色背景移除屏幕
if (currentY < -(backHeight - titleHeight)) {
llayoutLevelTitle.getBackground().mutate().setAlpha(255);
}
}
备注:代码比较完整,关键位置都有注释,就不做过多的解释。