2017-03-15 324 views
0

我希望imageview只能在屏幕尺寸內拖動。但下面的代碼的問題是,只有左邊距和上邊距停止imageview,如何實現if語句的右邊界和底邊界,以便它阻止視圖離焦。下面是代碼,在此先感謝android:在佈局尺寸(sceen尺寸)內拖動視圖

  public boolean onTouch(View view, MotionEvent event) { 

      DisplayMetrics displaymetrics = new DisplayMetrics(); 
      getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); 
      float screenHeight = displaymetrics.heightPixels; 
      float screenWidth = displaymetrics.widthPixels; 

      final int x = (int) event.getRawX(); 
      final int y = (int) event.getRawY(); 

      if(view==image1){ 
       switch (event.getAction() & MotionEvent.ACTION_MASK) { 

        case MotionEvent.ACTION_DOWN: 
         LinearLayout.LayoutParams lParams = (LinearLayout.LayoutParams) 
           view.getLayoutParams(); 
         xDelta = x - lParams.leftMargin; 
         yDelta = y - lParams.topMargin; 
         x1Delta = lParams.rightMargin; 
         y2Delta = lParams.bottomMargin; 
         break; 

        case MotionEvent.ACTION_UP:       
         break; 

        case MotionEvent.ACTION_MOVE: 
         LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) view 
           .getLayoutParams(); 
         //below leftMargin , topMargin works fine 
         if((x - xDelta) > 0 && (x - xDelta) < screenWidth){layoutParams.leftMargin = x - xDelta;} 
         if((y - yDelta) > 0 && (y - yDelta) < screenHeight){layoutParams.topMargin = y - yDelta;} 
         layoutParams.rightMargin = 0;//how to make this stops the imageview on rightMargin 
         layoutParams.bottomMargin = 0;//how to make this stops the imageview on bottomMargin 
          view.setLayoutParams(layoutParams); 
         break; 
       } 
       mainLayout.invalidate(); 
      } 
      return true; 
     } 
    }; 

回答

0

經過長期的研究,我發現自己的答案,我也改變LinearLayoutAbsoluteLayout後..

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

       switch (event.getAction() & MotionEvent.ACTION_MASK) { 

        case MotionEvent.ACTION_DOWN: 
         xDelta = event.getX(); 
         yDelta = event.getY(); 
         break; 

        case MotionEvent.ACTION_POINTER_DOWN: 
         oldDist = spacing(event); 
         if (oldDist > 10f) { 
          mode = ZOOM; 
         } 

        case MotionEvent.ACTION_UP: 
         break; 

        case MotionEvent.ACTION_MOVE: 
         x1Delta = event.getX() - xDelta ; 
         y2Delta = event.getY() - yDelta; 

         m_posX = m_prevX + x1Delta; 
         m_posY = m_prevY + y2Delta; 

         if (m_posX > 0 && m_posY > 0 && (m_posX + view.getWidth()) < mainLayout.getWidth() && (m_posY + view.getHeight()) < mainLayout.getHeight()) 
         { 
          view.setLayoutParams(new AbsoluteLayout.LayoutParams(view.getMeasuredWidth(), view.getMeasuredHeight(), (int) m_posX, (int) m_posY)); 

          m_prevX = m_posX; 
          m_prevY = m_posY; 
         } 

         break; 
       } 
       mainLayout.invalidate(); 
      return true; 
     } 
    };