I want the imageview
to be draggable only within the screen size . But the problem with the below code is , only left and top margin stops the imageview
,how to implement if statement for right and bottom margin so that it stops the view from going out of focus. below is the code , Thanks in advance
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;
}
};
After a Long research I found the answer myself and I also changed LinearLayout
to AbsoluteLayout
..
@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;
}
};