2013-06-18 99 views
0

我有imageView。 ImageView具有圖像。當我移動imageView時,圖像運動不正常。我提到了其他一些教程,但沒有幫助。當我移動圖像向左,其移動下跌ImageView無法正常移動

代碼:

imageView.setOnTouchListener(new View.OnTouchListener() { 



     @Override 
     public boolean onTouch(View v, MotionEvent event) { 
      // TODO Auto-generated method stub 
      layoutParams = (RelativeLayout.LayoutParams) imageView.getLayoutParams(); 

       switch(event.getAction())     
       { 
        case MotionEvent.ACTION_DOWN: 

         break; 

        case MotionEvent.ACTION_MOVE: 

         int x_cord = (int) event.getRawX(); 
         int y_cord = (int) event.getRawY(); 

        System.out.println("value of x" +x_cord); 
        System.out.println("value of y" +y_cord);   


         if (x_cord > windowwidth) { 
          x_cord = windowwidth; 
          } 
         if (y_cord > windowheight) { 
          y_cord = windowheight; 
          } 


        layoutParams.leftMargin = x_cord+25; 
        layoutParams.rightMargin = y_cord+25; 

       imageView.setLayoutParams(layoutParams); 
          break; 
        default: break; 
        } 
        return true; 
     } 
    }); 

回答

1
@Override 
public boolean onTouch(View v, MotionEvent event){ 
     switch(event.getAction()) 
     { 
      case MotionEvent.ACTION_DOWN : 
      { 
       x = event.getX(); 
            y = event.getY(); 
       dx = x-myView.getX(); 
       dy = y-myView.getY(); 
      } 
      break; 
      case MotionEvent.ACTION_MOVE : 
      { 
       myView.setX(event.getX()-dx); 
       myView.setY(event.getY()-dy); 
      } 
      break; 
      case MotionEvent.ACTION_UP : 
      { 
       //your stuff 
      } 
     return true; 
} 

對於API 8:

RelativeLayout.LayoutParams parms; 
LinearLayout.LayoutParams par; 
float dx=0,dy=0,x=0,y=0; 

@Override 
public boolean onTouch(View v, MotionEvent event) { 
    switch(event.getAction()) 
    { 
     case MotionEvent.ACTION_DOWN : 
     { 
      parms = (LayoutParams) myView.getLayoutParams(); 
      par = (LinearLayout.LayoutParams) getWindow().findViewById(Window.ID_ANDROID_CONTENT).getLayoutParams(); 
      dx = event.getRawX() - parms.leftMargin; 
      dy = event.getRawY() - parms.topMargin; 
     } 
     break; 
     case MotionEvent.ACTION_MOVE : 
     { 
      x = event.getRawX(); 
      y = event.getRawY(); 
      parms.leftMargin = (int) (x-dx); 
      parms.topMargin = (int) (y - dy); 
      myView.setLayoutParams(parms); 
     } 
     break; 
     case MotionEvent.ACTION_UP : 
     { 

     } 
     break; 
    } 
    return true; 
} 
+0

它working..thanks – user2474320

+0

如何使用此代碼裏面捏? – user2474320