在工作中遇到了这个问题,拖动一个图片按钮,切换页面后发现按钮又回到了原始的位置.
百度了下大致方法多为一种,即通过重写onTouchEvent()记录前后移动的相对坐标,然后根据相对坐标设置控件位置
代码如下(示例):
@Override
public boolean onTouch(View view, MotionEvent event) {
//得到事件的坐标
int eventX = (int) event.getRawX();
int eventY = (int) event.getRawY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
//得到父视图的right/bottom
if (maxRight == 0) {//保证只赋一次值
maxRight = parentView.getRight();
maxBottom = parentView.getBottom();
}
//第一次记录lastX/lastY
lastX = eventX;
lastY = eventY;
isMove = false;
downTime = System.currentTimeMillis();
if (haveDelay()) {
canDrag = false;
} else {
canDrag = true;
}
break;
case MotionEvent.ACTION_MOVE:
if (haveDelay() && !canDrag) {
long currMillis = System.currentTimeMillis();
if (currMillis - downTime >= delay) {
canDrag = true;
}
}
if (!canDrag) {
break;
}
//计算事件的偏移
int dx = eventX - lastX;
int dy = eventY - lastY;
if (dx != 0 && dy != 0) {
//根据事件的偏移来移动imageView
int left = view.getLeft() + dx;
int top = view.getTop() + dy;
int right = view.getRight() + dx;
int bottom = view.getBottom() + dy;
//限制left >=0
if (left < 0) {
right += -left;
left = 0;
}
//限制top
if (top < 0) {
bottom += -top;
top = 0;
}
//限制right <=maxRight
if (right > maxRight) {
left -= right - maxRight;
right = maxRight;
}
//限制bottom <=maxBottom
if (bottom > maxBottom) {
top -= bottom - maxBottom;
bottom = maxBottom;
}
//不要这么设置View.layout(int left,int top,int right,int bottom)方法
// view.setLeft(left);
// view.setTop(top);
// view.setRight(right);
// view.setBottom(bottom);
//要用setLayoutParams这么设置
setViewLocation(view, left, top, right, bottom);
//再次记录lastX/lastY
lastX = eventX;
lastY = eventY;
isMove = true;
}
break;
default:
break;
}
return isMove;
}
代码如下(示例):
private static void setViewLocation(View view, int left, int top, int right, int bottom) {
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(right - left, bottom - top);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
ViewParent parent = view.getParent();
View p = (View) parent;
int marginRight = p.getWidth() - right;
int marginBottom = p.getHeight() - bottom;
params.setMargins(left, top, marginRight, marginBottom);
view.setLayoutParams(params);
}
以上就是今天要讲的内容,本文主要实现ImageView拖拽时限制区域及解决切换页面时ImageView位置重置问题。