计算listView滑动距离的方法:
public int getScroll() { View c = this.getChildAt(0); if (c == null) { return 0; } int firstVisiblePosition = this.getFirstVisiblePosition(); int top = c.getTop(); return -top + firstVisiblePosition * c.getHeight() ; }当listView的OnScrollLsitener无法监听时,我们需要不断获取listView的滚动距离,此时,如果写在OnTouchEvent中的话,会出现只有手指放在屏幕上滚动时,才会不断获取listView的滚动距离,一旦手指离开屏幕,这个距离就会停止在手指离开的地方:如下代码是不正确的:
@Override public boolean onTouchEvent(MotionEvent ev) { int action = ev.getAction(); switch (action) { case MotionEvent.ACTION_MOVE: distance = ev.getY() - startY;所以我们需要将if (onScrolllingTitleColor != null) { onScrolllingTitleColor.onScrolling(getScroll()); }break; } return super.onTouchEvent(ev); }
这个方法写在listView能不断调用的方法里;getScroll();
onScrollChanged(在ScrollView中,这个方法会返回滚动的距离,即:t 的值,可是listView复写此方法并不能获得 t 的值,看了listView的onScrollListener的方法:int l, int t, int oldl, int oldt);
public void setOnScrollListener(OnScrollListener l) { mOnScrollListener = l; invokeOnItemScrollListener(); }看看红色字体,这个方法干了什么呢?
void invokeOnItemScrollListener() { if (mFastScroll != null) { mFastScroll.onScroll(mFirstPosition, getChildCount(), mItemCount); } if (mOnScrollListener != null) { mOnScrollListener.onScroll(this, mFirstPosition, getChildCount(), mItemCount); } onScrollChanged(0, 0, 0, 0); // dummy values, View's implementation does not use these. }看到了吗?
onScrollChanged(0, 0, 0, 0);
这句代码,将所有的值置为了0,所以listView复写此方法所得到的值全部为零,可是我需要不断获取listView的滚动距离,怎么办呢?
虽然它里面的参数的值都为零,可是却是一直被调用的,真是糊涂了,咱们有没有用里面的值,也怪自己一直想着用里面的值判断,死脑筋了,既然这个方法一直被调用,那么,我们把获取listView滚动距离的方法写在这个回调里,不就一直能获取了吗?于是乎:
@Override protected void onScrollChanged(int l, int t, int oldl, int oldt) { super.onScrollChanged(l, t, oldl, oldt); if (onScrolllingTitleColor != null) { onScrolllingTitleColor.onScrolling(getScroll()); } }
onScrollingTitleColor是一个回调接口对象,里面有一个参数,传入的就getScroll方法得到的listView的滚动距离,接口如下:
/** * 上滑标题栏变色 */ public interface OnScrollingTitleColor { void onScrolling(int position); } private OnScrollingTitleColor onScrollingTitleColor; public void setOnScrollingChangeTitleColor(OnScrollingTitleColor onScrollingTitleColor) { this.onScrollingTitleColor = onScrollingTitleColor; }
在activity中实现OnScrollingTitleColor接口,实现onScrolling方法,不断改变标题栏颜色
@Override public void onScrolling(int position) { if (position <= 0) { ll_action_btn.setBackgroundColor(Color.argb((int) 0, 18, 183, 245)); } else if (position > 0 && position <= imageHeight) { float scale = (float) position / imageHeight; float alpha = (255 * scale); ll_action_btn.setBackgroundColor(Color.argb((int) alpha, 18, 183, 245)); } else { ll_action_btn.setBackgroundColor(Color.rgb((int) 18, 183, 245)); } }