Gallery关于滚动

1.默认Gallery的滚动轻轻一滑动就会滚动好多张图片 通过重写onFling方法返回false可以解决

@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		return false;
	}


2.解决每次只滚动一张图片后 又会发现 手指滑动很长才能滑动到下一张 有时候还滑不过去 这时需要这样写

@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		int kEvent;
		if (isScrollingLeft(e1, e2)) {
			kEvent = KeyEvent.KEYCODE_DPAD_LEFT;
		} else {
			kEvent = KeyEvent.KEYCODE_DPAD_RIGHT;
		}
		onKeyDown(kEvent, null);
		return false;
	}

	private boolean isScrollingLeft(MotionEvent e1, MotionEvent e2) {
		return e2.getX() > e1.getX();
	}


3.如何通过按钮来让Gallery滚动

/*
 * 只是部分代码
 * rightBtn是下一页按钮对象
 * leftBtn是上一页按钮对象
 * customGallery是自定义Gallery对象
 */
rightBtn.setOnClickListener(new OnClickListener() {

	@Override
	public void onClick(View v) {
		customGallery.onScroll(null, null, 1 * (20+500), 0);
		customGallery.onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, null);
	}
});

leftBtn.setOnClickListener(new OnClickListener() {

	@Override
	public void onClick(View v) {
		customGallery.onScroll(null, null, -1 * (20+500), 0);
		customGallery.onKeyDown(KeyEvent.KEYCODE_DPAD_LEFT, null);
	}
});


4.怎么取消Gallery手指滑动滚动 如果只希望通过按钮滚动 不想通过手指滑动可能就会需要这样做

private boolean stuck = false;

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

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

	public CustomGallery(Context context) {
		super(context);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		return stuck || super.onTouchEvent(event);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_DPAD_LEFT:
		case KeyEvent.KEYCODE_DPAD_RIGHT:
			return stuck || super.onKeyDown(keyCode, event);
		}
		return super.onKeyDown(keyCode, event);
	}

	public void setScrollingEnabled(boolean enabled) {
		stuck = !enabled;
	}
然后在实例化自定义Gallery调用setScrollingEnabled方法来控制是否可以用手指滑动
customGallery = (CustomGallery) findViewById(R.id.customGallery);
customGallery.setScrollingEnabled(false);//取消滑动


5.结合3和4 就可以实现只通过按钮来控制图片的滚动

/*
 * 只是部分代码
 * rightBtn是下一页按钮对象
 * leftBtn是上一页按钮对象
 * customGallery是自定义Gallery对象
 */
rightBtn.setOnClickListener(new OnClickListener() {

	@Override
	public void onClick(View v) {
		customGallery.setScrollingEnabled(true);
		customGallery.onScroll(null, null, 1 * (20+500), 0);
		customGallery.onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, null);
		customGallery.setScrollingEnabled(false);
	}
});

leftBtn.setOnClickListener(new OnClickListener() {

	@Override
	public void onClick(View v) {
		customGallery.setScrollingEnabled(true);
		customGallery.onScroll(null, null, -1 * (20+500), 0);
		customGallery.onKeyDown(KeyEvent.KEYCODE_DPAD_LEFT, null);
		customGallery.setScrollingEnabled(false);
	}
});



你可能感兴趣的:(Gallery关于滚动)