2017-04-13 107 views
0

我只想在Y方向上拖放一個按鈕。我實現了這個功能。但它跨越屏幕邊界並消失。請幫助我實現我的目標。拖放一個按鈕?

這裏是我的代碼

public class ChoiceTouchListener implements View.OnTouchListener{ 

    @Override 
    public boolean onTouch(View view, MotionEvent motionEvent) { 

     int x = (int) motionEvent.getRawX(); 
     int y = (int) motionEvent.getRawY(); 
     DisplayMetrics metrics = getResources().getDisplayMetrics(); 


     switch (motionEvent.getAction() & MotionEvent.ACTION_MASK){ 
      case MotionEvent.ACTION_DOWN: 
       RelativeLayout.LayoutParams tparams = (RelativeLayout.LayoutParams) view.getLayoutParams(); 
       changey = y- tparams.topMargin; 
       break; 
      case MotionEvent.ACTION_UP: 
       break; 
      case MotionEvent.ACTION_POINTER_DOWN: 
       break; 
      case MotionEvent.ACTION_POINTER_UP: 
       break; 
      case MotionEvent.ACTION_MOVE: 
       RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) view.getLayoutParams(); 


       params.topMargin = y-changey; 

       view.setLayoutParams(params); 
       break; 
     } 

     rootlayout.invalidate(); 

     return true; 
    } 
} 

回答

1

您可以使用此做出限制在屏幕邊界的視圖。

int width=cropperLayout.getLayoutParams().width;; 
     int height=cropperLayout.getLayoutParams().height; 
     switch (event.getAction()) { 

      case MotionEvent.ACTION_DOWN: 

       dX = v.getX() - event.getRawX(); 
       dY = v.getY() - event.getRawY(); 

       return true; 

      case MotionEvent.ACTION_MOVE: 

       if (width == windowWidth && height == windowHeight){} 
       else { 
        v.animate() 
          .x(event.getRawX() + dX) 
          .y(event.getRawY() + dY) 
          .setDuration(0) 
          .start(); 

        if (event.getRawX() + dX + width > windowWidth) { 
         v.animate() 
           .x(windowWidth - width) 
           .setDuration(0) 
           .start(); 
        } 
        if (event.getRawX() + dX < 0) { 
         v.animate() 
           .x(0) 
           .setDuration(0) 
           .start(); 
        } 
        if (event.getRawY() + dY + height > windowHeight) { 
         v.animate() 
           .y(windowHeight - height) 
           .setDuration(0) 
           .start(); 
        } 
        if (event.getRawY() + dY < 0) { 
         v.animate() 
           .y(0) 
           .setDuration(0) 
           .start(); 
        } 

        return true; 
       } 
+0

什麼是你的代碼中的「v」? – Hasnain

+0

查看onTouch的參數。您可以在onTouch中編寫代碼並通過查看 – Anmol

+0

來代替v。讓我試試這個代碼。 – Hasnain