3

我正在嘗試使用onTouchListener使imageview可拖動。這是我迄今爲止的代碼拖動Android如何在relativelayout中拖動imageview,然後將其放回原位

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'是imageview。我得到的問題是,getRawX和getRawY沒有返回正確的座標(我認爲...)。當我嘗試觸摸圖像然後嘗試拖動它時,圖像開始從另一個位置拖動。通常比原來的位置更高,更多。的ImageView的處於RelativeLayout的和當移動開始我使用API​​ 10

+0

喜看看這個樣本http://androidrox.wordpress.com/2011/05/13/android-sample-app-拖放圖像使用觸摸/ – itsrajesh4uguys

回答

1

需要得到抵消的RelativeLayout和屏幕

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); 
2

,需要的偏移量(即x_offsety_offset)與ImageView的初始位置進行初始化。

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

這從不是從你的ImageView開始不同的位置開始停止你的拖累:

然後,如下此舉應該進行修改。

+0

我剛剛嘗試過,並更新了我的代碼,但我仍然遇到同樣的問題。圖像開始從一個不同的位置移動,比當我沒有放置偏移量時,但仍然從原始位置不同的位置開始 – user2230558

+0

在'case MotionEvent.ACTION_DOWN'的代碼塊之後需要'bre​​ak' 。 –

+0

o我正在刪除大量的ACTION_DOWN和ACTION_MOVE之間的評論,我刪除了這個break;以及。我更新了我的代碼 – user2230558

相關問題