一種是使用ScrollView和HorizontalScrollView結合。
這種方式的話,斜向滑動會有先後次序,一般將ScrollView放在外層
第二種,使用onTouchEvent方法,監聽移動事件,進行處理。
如果只是監聽移動事件,圖片可以移出指定地區之外,可以通過控制邊界來進行限制在一定範圍內移動。
簡單解決方案代碼如下:
container.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: { currentX = (int) event.getRawX(); currentY = (int) event.getRawY(); break; } case MotionEvent.ACTION_MOVE: { int x2 = (int) event.getRawX(); int y2 = (int) event.getRawY(); // 限制移動的邊界======================== int[] imageLocation = new int[2]; int[] containerLocation = new int[2]; // 取得 圖片和Layout的座標 image.getLocationOnScreen(imageLocation); container.getLocationOnScreen(containerLocation); // 向右 currentX - x2 < 0 // 向左 currentX - x2 > 0 // 向上 currentY - y2 > 0 // 向下 currentY - y2 < 0 if (currentX - x2 > 0) { //當向左移動時 if (imageLocation[0] +image.getRight() > containerLocation[0] + container.getRight()) { container.scrollBy(currentX - x2 , 0); } else { container.scrollTo(image.getWidth() - container.getWidth(), containerLocation[1] - imageLocation[1]); // y2不正確 } } else { Log.e("scroll path", "向右移動"); if (imageLocation[0] < containerLocation[0]) { container.scrollBy(currentX - x2 , 0); } else { container.scrollTo(0, containerLocation[1] - imageLocation[1]); } } if (currentY - y2 > 0) { Log.e("scroll path", "向上移動"); if (image.getBottom() + imageLocation[1] > containerLocation[1] +container.getBottom()) { container.scrollBy(0 , currentY - y2); } else { container.scrollTo(containerLocation[0] - imageLocation[0], image.getHeight() - container.getWidth()); } } else { Log.e("scroll path", "向下移動"); if (imageLocation[1] < containerLocation[1]) { container.scrollBy(0 , currentY - y2); } else { container.scrollTo(containerLocation[0] - imageLocation[0], 0); } } // 限制移動的邊界======================== // 無限制移動的邊界======================== //container.scrollBy(currentX - x2 , currentY - y2); // 無限制移動的邊界======================== currentX = x2; currentY = y2; break; } case MotionEvent.ACTION_UP: { break; } } return true; } });