android listview onTouch和onItemClick并存

问题:根据手指是滑动还是单击,决定触发onTouch还是onItemClick。。滑动触发onTouch事件,单击触发onItemClick事件。。

解决:根据onTouch返回的值判断,如果返回true,不触发onItemClick。返回false,则触发onItemClick。在onTouch中会依次触发down,move,up操作。。所以可以在up里面判断,如果移动距离=0,就是单击了,返回false,触发onItemClick。如果移动距离!=0,就返回true。

/**
	 * 根据手指滑动,控件做出相应的滑动
	 * 
	 * @param event
	 * @return
	 */
	public boolean onMove(MotionEvent event) {
		RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) content.getLayoutParams();
		boolean result = false;
		switch (event.getAction()) {
		case MotionEvent.ACTION_UP:
			float upX = event.getX();
			System.out.println("--我移动了" + moveX + "距离--");
			if ((upX - downX) != 0) {
				if (layoutParams.leftMargin > MAX_WIDTH / 2) {  //滑动不到一半距离,缩回
					new AsynMove().execute(SPEED);
				} else {
					new AsynMove().execute(-SPEED);
				}
				result = true; // 存在滑动距离,不触发item点击事件。。
			} else {
				result = false;
			}
			break;
		case MotionEvent.ACTION_DOWN: // 单击
			System.out.println("我在单击,返回false,进入item点击事件");
			downX = event.getX();
			result = false;
			break;
		case MotionEvent.ACTION_MOVE:
			moveX = event.getX() - downX;
			layoutParams.leftMargin += moveX;
			layoutParams.rightMargin -= moveX;
			if (layoutParams.leftMargin <= 0) {  //设置最小值和最大值,使之不会滑动过了头
				layoutParams.leftMargin = 0;
				layoutParams.rightMargin = 0;

			} else if (layoutParams.leftMargin >= MAX_WIDTH) {
				layoutParams.leftMargin = MAX_WIDTH;
				layoutParams.rightMargin = -MAX_WIDTH;
			}
			System.out.println("--我在滑动-leftMargin: " + layoutParams.leftMargin + " rightMargin: " + layoutParams.rightMargin);
			result = true;
			break;
		}
		content.setLayoutParams(layoutParams);
		return result;
	}


你可能感兴趣的:(listview,onTouch,onItemClick,并存,android)