listview上进行ontouch事件,可滑动,可点击页面跳转


最近在做一个listview上面点击事件,需求是可以上下滑动,点击的时候不能触发onitem事件而是跳转。
头疼了许久,今天终于弄出来了,给大家分享下

(代码参考了http://yzhong-sa.iteye.com/blog/648807这个哥们的,然后我稍加改动)

ListView list = (ListView) findViewById(R.id.listview);
		String[] items = { "One", "Two", "Three", "Four", "Five", "Six",
				"Serven", "One", "Two", "Three", "Four", "Five", "Six",
				"Serven", "One", "Two", "Three", "Four", "Five", "Six",
				"Serven" };
		list.setAdapter(new ArrayAdapter(this,
				android.R.layout.simple_list_item_1, items));
		list.setOnTouchListener(new OnTouchListener() {
			int lastX, curX;
			private int totalMove = 0;
			private boolean firstDown = true;// 开关
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN: {
					lastX = (int) event.getX();
					totalMove = 0;
					firstDown = false;
					return false;
				}
				case MotionEvent.ACTION_MOVE: {
					if (firstDown) {
						curX = (int) event.getX();
						totalMove = 0;
						firstDown = false;
					}
					curX = (int) event.getX();
					int delatX = curX - lastX;
					// if (delatX > 0) {
					totalMove += delatX;
					lastX = curX;
					// }
					return false;
				}
				case MotionEvent.ACTION_UP: {
					boolean result = false;
					if (totalMove > 20) {
						//
						Log.e("right", "right");
						totalMove = 0;
						return result = true;
					}
					else if (totalMove < 0 && Math.abs(totalMove) > 20) {
						Log.e("left", "left");
						totalMove = 0;
						return result = true;
					}
					else{
						//当作onclick用 用作跳转
						//防止他滑动一段距离后,会停一会儿
						if(Math.abs(totalMove)<2){
							Intent t = new Intent();
							t.setClass(ListViewClickActivity.this,BActivity.class);
							startActivity(t);
							result = true;
						}
					}
					return result;
				}
				}
				return false;
			}
		});


你可能感兴趣的:(android,listview)