public class BCustomerLinearLayout extends LinearLayout implements View.OnTouchListener {
private static final String TAG = "CustomerLinearLayout";
public OnGestureChangeListener listener;
public interface OnGestureChangeListener {
void scrollLeft();
void scrollRight();
// void onClick();
}
public void setOnGestureChangeListener(OnGestureChangeListener listener) {
this.listener = listener;
}
public BCustomerLinearLayout(Context context) {
this(context, null);
}
public BCustomerLinearLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public BCustomerLinearLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
//setGestureListener();
//设置Touch监听
this.setOnTouchListener(this);
//允许长按
this.setLongClickable(true);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
final int action = event.getAction();
switch (action){
case MotionEvent.ACTION_DOWN:
Log.e(TAG, "event down!");
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
Log.e(TAG, "event : up");
float dx = touchDownX - event.getX();
Log.e(TAG, "dx:" + dx);
if (dx < -ViewConfiguration.get(
getContext()).getScaledPagingTouchSlop()) {
// Fling enough to move left
Log.e(TAG, "snap right");
if (null!=listener){
listener.scrollRight();
}
return true;
} else if (dx > ViewConfiguration.get(
getContext()).getScaledPagingTouchSlop()){
// Fling enough to move right
Log.e(TAG, "snap left");
if (null!=listener){
listener.scrollLeft();
}
return true;
} else {
Log.e(TAG, "snap click");
return super.onTouchEvent(event);
// if (null!=listener){
// listener.onClick();
// }
}
}
return super.onTouchEvent(event);
}
private boolean mScrolling;
private float touchDownX;
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touchDownX = event.getX();
mScrolling = false;
break;
case MotionEvent.ACTION_MOVE:
//getScaledTouchSlop是一个距离,表示滑动的时候,手的移动要大于这个距离才识别为滑动事件
if (Math.abs(touchDownX - event.getX()) >= ViewConfiguration.get(
getContext()).getScaledTouchSlop()) {
mScrolling = true;
} else {
mScrolling = false;
}
break;
case MotionEvent.ACTION_UP:
mScrolling = false;
break;
}
return mScrolling;
}
}