代码如下:
1 private ImageView mShowImage = (ImageView) findViewById(R.id.mShowImage); 2 3 mShowImage.setOnTouchListener(new View.OnTouchListener() { 4 int startX = 0,startY = 0;//触摸屏幕时候得相对于ImageView的X,Y坐标 5 int mX = 0, mY=0;//ImageView对于屏幕的左边距和右边距 6 @Override 7 public boolean onTouch(View v, MotionEvent e) { 8 switch (e.getAction()) 9 { 10 case MotionEvent.ACTION_DOWN: 11 startX = (int) e.getX(); 12 startY = (int) e.getY(); 13 break; 14 case MotionEvent.ACTION_MOVE: 15 mX = (int) (e.getRawX() - startX);//当前触摸关于屏幕的X坐标减去关于ImageView的X坐标就是ImageView的左边距 16 mY = (int) (e.getRawY() - startY - getStatusBarHeight());//跟左边距原理相同,不过需要减去通知栏的高度,若全屏,则不需要减去通知栏高度 17 v.layout(mX,mY,mX+v.getWidth(),mY+v.getHeight()); 18 break; 19 } 20 return true; 21 } 22 }); 23 24 25 //获取通知栏高度 26 private int getStatusBarHeight(){ 27 Rect rect = new Rect(); 28 getWindow().getDecorView().getWindowVisibleDisplayFrame(rect); 29 return rect.top; 30 }