Android 实现滑动的几种方法(一)onLayout方法 和 offsetLeftAndRight()与offsetTopAndBottom();

时间:2022-03-29 23:20:10

onLayout方法:

package com.example.administrator.myapplication;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

/**
* Created by Administrator on 2015/11/22 0022.
*/

public class MyView extends View {
int lastX ;
int lastY ;
public MyView(Context context) {
super(context);
}

public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();

switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
lastX = x;
lastY = y;
break;

case MotionEvent.ACTION_MOVE:
int offx = x - lastX;
int offy = y - lastY;

// layout(getLeft() + offx, getTop() + offy
// , getRight() + offx, getBottom() + offy);
// 同时偏移(与layout 方法效果一样)
offsetLeftAndRight(offx);
offsetTopAndBottom(offy);
/*
* 注意:一定要重新设置坐标,这样才能准确地获取偏移量
*/

lastX = x;
lastY = y;

break;
}
return true;//记得返回true,说明被我们这里消化了改事件
}

}