ListView头部视差效果
当点击一个listView向下滑动时,listView头部的图片会缓慢向下移动,给人的感觉是很”吃力”的向下显示出来
原理
当给一个listView添加一个imageView作为HeadView时,动态控制此imageView的显示高度,并控制其高度的变化率小于手指在y轴移动的距离变化率,从而给人一种“吃力”的感觉。
事例代码
public class myListView extends ListView {
private ImageView headImageView;
private int orignalHeight;
private int maxHeight;
public myListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ParallaxListView(Context context) {
super(context);
}
//设置头部imageView
public void setHeadImageView(ImageView headView) {
this.headImageView = headView;
init();
}
//获取headImageView的原始高度,以及最大显示高度
private void init() {
if (headImageView != null) {
headImageView.getViewTreeObserver().addOnGlobalLayoutListener(
new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
headImageView.getViewTreeObserver()
.removeGlobalOnLayoutListener(this);
orignalHeight = headImageView.getHeight();
int drawableHeight = headImageView.getDrawable()
.getIntrinsicHeight();
//当我们设置的图片较小时,该图片不能向下“拉”,因此设置其最大显示高度为我们自定义显示高度的倍数
maxHeight = orignalHeight > drawableHeight ? orignalHeight
: drawableHeight * 3;
}
});
}
}
/**
* 在listview滑动到头的时候执行,可以获取到继续滑动的距离和方向
* <p>
* deltaX:x方向继续滑动的距离
* <p>
* deltaY:y方向继续滑动的距离(负:listView头部到头且向下滑动 正:listView尾部到头且向上滑动)
* <p>
* maxOverScrollX:x方向可以滚动的最大距离
* <p>
* maxOverScrollY:y方向可以滚动的最大距离
* <p>
* isTouchEvent: true: 是手指拖动滑动 false:表示fling即靠惯性滑动;
*/
@Override
protected boolean overScrollBy(int deltaX, int deltaY, int scrollX,
int scrollY, int scrollRangeX, int scrollRangeY,
int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent) {
if (isTouchEvent && deltaY < 0) {
if (headImageView != null) {
int newHeight = headImageView.getHeight() - deltaY/3;//设置显示高度的变化率
if (newHeight > maxHeight) {
newHeight = maxHeight;
}
headImageView.getLayoutParams().height = newHeight;
headImageView.requestLayout();
}
}
return super.overScrollBy(deltaX, deltaY, scrollX, scrollY,
scrollRangeX, scrollRangeY, maxOverScrollX, maxOverScrollY,
isTouchEvent);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_UP) {
//让listView的headImageView归位 headImageView.getLayoutParams().height = orignalHeight;
headImageView.requestLayout();
}
return super.onTouchEvent(ev);
}
}