天天看点

Gallery中,取消惯性滑动,滑动一次只切换一个视图

用Gallery出现客户一需求, 说做图片展示时候,Gallery滑动后,由于惯性原因,会连续切换好几次,这个就需要改为滑动一次只切换一个视图

要实现这个效果就需要去自定义一个Gallery,实现起来还是蛮简单的,如下

public class OnePageGallery extends Gallery {
    public OnePageGallery(Context context) {
        super(context);
    }

    public OnePageGallery(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public OnePageGallery(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                           float velocityY) {
        if (velocityX > 0) {
            // 往左边滑动
            super.onKeyDown(KeyEvent.KEYCODE_DPAD_LEFT, null);
        } else {
            // 往右边滑动
            super.onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, null);
        }
        return false;
    }
}