3

我正在尝试使用 onTouchListener 使图像视图可拖动。这是我到目前为止用于拖动的代码

switch (ME.getAction()){
    case MotionEvent.ACTION_DOWN://IF USER PRESSED ON THE IMAGE

        origix = v.getLeft();   //save original x coordinate calculated with the offset
        origiy = v.getTop();
break;
case MotionEvent.ACTION_MOVE://IF USER IS MOVING THE IMAGE


            System.out.println("MOVED");
            int x_cord = (int)ME.getRawX(); //get coordinate of the user touch
            int y_cord = (int)ME.getRawY(); 

            //set the image to the new coordinates based on where the user is touching and dragging
            MarginLayoutParams marginParams = new MarginLayoutParams(v.getLayoutParams());   
            marginParams.setMargins(x_cord - origix, y_cord - origiy,0, 0);
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(marginParams);
            v.setLayoutParams(layoutParams);  
            MOVED = true;   //mark that the image has been move

    break;

变量“v”是图像视图。我得到的问题是 getRawX 和 getRawY 没有返回正确的坐标(我认为......)。当我尝试触摸图像然后尝试拖动它时,图像开始从另一个位置拖动。通常比原来的位置高得多,向右一点。图像视图在相对布局中,我正在使用 API 10

4

2 回答 2

2

移动开始时,您x_offset需要y_offset使用ImageView.

然后,移动应该修改如下:

marginParams.setMargins(x_cord - x_offset, y_cord - y_offset,0, 0);

这将阻止您从与开始位置不同的位置开始拖动ImageView

于 2013-04-01T05:41:05.957 回答
1

需要获取相对布局和屏幕的偏移量

int offsety = (screenheight - relheight); //screenheight is the height of the screen and rel height is the height of the relativelayout that the image is in then changed     
marginParams.setMargins(x_cord - origix, y_cord - origiy,0, 0); to this     
marginParams.setMargins(x_cord - (v.getWidth()/2), y_cord - offsety - (v.getHeight()/2),0, 0);
于 2013-04-14T03:18:05.460 回答