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;
}
};