---
title: "Gallery的onItemSelected方法中UI操作时滑动问题解决"
author: "Java-Object"
date: "2014-02-27T15:05:18Z"
tags: []
categories: ["编程语言"]
slug: "gallery-onitemselected-ui"
draft: false
lastmod: "2014-02-27T15:05:50Z"
id: 2023492
url: "https://hezd.iteye.com/blog/2023492"
---

最近在项目中使用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](http://stackoverflow.com/questions/8347965/android-gallery-onitemselected-causes-scrolling-to-snap)

             [http://code.google.com/p/android/issues/detail?id=16171](http://code.google.com/p/android/issues/detail?id=16171)