When dragging an Imageview goes outside the screen

前端 未结 1 486
盖世英雄少女心
盖世英雄少女心 2021-01-23 22:09

I want to implement a movable imageView when it is drag. The dragging is working perfectly alright. But when i drag to the end , the imageView goes out of the screen. H

1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-23 22:24

    After spend more time on it, finally find the best solution.

    Modify my OnTouch listerner section as :

     DisplayMetrics displaymetrics = new DisplayMetrics();
     getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
     screenHight = displaymetrics.heightPixels;
     screenWidth = displaymetrics.widthPixels;
    
      @SuppressLint("NewApi") @Override
      public boolean onTouch(View view, MotionEvent event) {
    
    
           float newX, newY;
    
        switch (event.getActionMasked()) {
          case MotionEvent.ACTION_DOWN:
    
            dX = view.getX() - event.getRawX();
            dY = view.getY() - event.getRawY();
            lastAction = MotionEvent.ACTION_DOWN;
            break;
    
          case MotionEvent.ACTION_MOVE:
    
              newX = event.getRawX() + dX;
              newY = event.getRawY() + dY;
    
          // check if the view out of screen
              if ((newX <= 0 || newX >= screenWidth-view.getWidth()) || (newY <= 0 || newY >= screenHight-view.getHeight()))
              {
                  lastAction = MotionEvent.ACTION_MOVE;
                  break;      
              }
    
            view.setX(newX);
            view.setY(newY);
    
            lastAction = MotionEvent.ACTION_MOVE;
    
            break;
    
          case MotionEvent.ACTION_UP:
            if (lastAction == MotionEvent.ACTION_DOWN)
              Toast.makeText(DraggableView.this, "Clicked!", Toast.LENGTH_SHORT).show();
            break;
    
          default:
            return false;
        }
        return true;
      }
    

    It's working perfectly :)

    0 讨论(0)
提交回复
热议问题