最近在项目中使用Gallery时重写onItemSelected方法并在里面进行UI操作,发现Gallery左右滑动时不流畅,跳跃感很强,折腾了好几天终于在stackoverflow上发现了解决办法,重写onlayout和onscroll方法。
废话少说上代码
package com.hzd.groupurchasing.view;
import android.content.Context;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.Gallery;
public class MyGallery extends Gallery {
private static final int OFFSETX = 100;
public MyGallery(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public MyGallery(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyGallery(Context context) {
super(context);
}
float startX;
private long mLastScrollEvent;
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b)
{
// XXX Hack alert!
// Ignore layout calls if we've had a scroll event in the last 250 msec;
// that'll ignore the per-second layout calls we get through BooPlayerView's
// updating.
long now = SystemClock.uptimeMillis();
if (Math.abs(now - mLastScrollEvent) > 250) {
super.onLayout(changed, l, t, r, b);
}
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
{
mLastScrollEvent = SystemClock.uptimeMillis();
return super.onScroll(e1, e2, distanceX, distanceY);
}
}
原地址:http://stackoverflow.com/questions/8347965/android-gallery-onitemselected-causes-scrolling-to-snap