该类的功能是实现随手指滑动切换页面的功能,类似Gallery(但是Gallery限制太多,比如每页布局必须相同)。有的同学可能会想到我们可以在 onTouchEvent (MotionEvent event)方法中进行判断,当左右滑动时,执行startActivity(Context context)方法达到切换页面的效果。但是使用这种方法进行切换是没有过度效果的,只是刷的一下就过去了,而使用这个继承了ViewGroup的布局就可以达到这个效果了。如下图所示:
ScrollLayout类代码
public class ScrollLayout extends ViewGroup {
// private float startX;
// private float startY;
public static boolean startTouch = true;
// private boolean canMove = true;
private static final String TAG = "ScrollLayout";
private Scroller mScroller;
/*
* 速度追踪器,主要是为了通过当前滑动速度判断当前滑动是否为fling
*/
private VelocityTracker mVelocityTracker;
/*
* 记录当前屏幕下标,取值范围是:0 到 getChildCount()-1
*/
private static int mCurScreen;
// private int mDefaultScreen = 1;
/*
* Touch状态值 0:静止 1:滑动
*/
private static final int TOUCH_STATE_REST = 0;
private static final int TOUCH_STATE_SCROLLING = 1;
/*
* 记录当前touch事件状态--滑动(TOUCH_STATE_SCROLLING)、静止(TOUCH_STATE_REST 默认)
*/
private int mTouchState = TOUCH_STATE_REST;
private static final int SNAP_VELOCITY = 600;
/*
* 记录touch事件中被认为是滑动事件前的最大可滑动距离
*/
private int mTouchSlop;
/*
* 记录滑动时上次手指所处的位置
*/
private float mLastMotionX;
private float mLastMotionY;
private OnScrollToScreenListener onScrollToScreen = null;
public ScrollLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ScrollLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mScroller = new Scroller(context);
// mCurScreen = mDefaultScreen;
mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
System.out.println("aaaaaaaaaaaaaaaaaaaaa" + mTouchSlop);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int childLeft = 0;
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View childView = getChildAt(i);
if (childView.getVisibility() != View.GONE) {
final int childWidth = childView.getMeasuredWidth();
childView.layout(childLeft, 0, childLeft + childWidth,
childView.getMeasuredHeight());
childLeft += childWidth;
}
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Log.e(TAG, "onMeasure");
super.onMeasure(widthMeasureSpec, heightMeasureSpec);