我们先来看看效果图:
上述截图,是手指拖动的效果,如果拖动过屏幕中点,松手后就会自动移动到第二屏。另外,如果使用轻扫手势,也可以自动移动下一屏。
Android中的 View有两个子类, Widget和 ViewGroup, Widget是可见的窗口组件,比如按钮, ViewGroup就是布局, ViewGroup已经提供了多个布局子类,比如 LinearLayout等。
本例中实现了自己的 ViewGroup子类。通过覆盖 onLayout方法实现对子视图的横向排列布局:
Java代码:
复制代码
通过覆盖 computeScroll方法,计算移动屏幕的位移和重新绘制屏幕:
Java代码:
复制代码
编写了一个名为 scrollToScreen的方法,用于根据指定屏幕号切换到该屏幕:
Java代码:
复制代码
snapToDestination方法,是处理当屏幕拖动到一个位置松手后的处理:
Java代码:
复制代码
然后说说手势事件的处理。 eric的实现,全部使用 onTouch事件处理,这样代码不够简明。因为需要记录很多组合手势的历史数据,这样就必须有一些状态位,一些坐标数值。
我用 GestureDetector的手势处理事件简化了这方面的处理,只在手势抬起( UP)事件处理中在 ouTouchEvent方法中做了处理。
上述截图,是手指拖动的效果,如果拖动过屏幕中点,松手后就会自动移动到第二屏。另外,如果使用轻扫手势,也可以自动移动下一屏。
Android中的 View有两个子类, Widget和 ViewGroup, Widget是可见的窗口组件,比如按钮, ViewGroup就是布局, ViewGroup已经提供了多个布局子类,比如 LinearLayout等。
本例中实现了自己的 ViewGroup子类。通过覆盖 onLayout方法实现对子视图的横向排列布局:
Java代码:
- package eoe. result;
- @Override
- protected void onLayout(boolean changed, int left, int top, int right,
- int bottom) {
- Log.d(TAG, ">>left: " + left + " top: " + top + " right: " + right
- + " bottom:" + bottom);
- /**
- * 设置布局,将子视图顺序横屏排列
- */
- for (int i = 0; i < getChildCount(); i++) {
- View child = getChildAt(i);
- child.setVisibility(View.VISIBLE);
- child.measure(right – left, bottom – top);
- child.layout(0 + i * getWidth(), 0, getWidth() + i * getWidth(),
- getHeight());
通过覆盖 computeScroll方法,计算移动屏幕的位移和重新绘制屏幕:
Java代码:
- package eoe. result;
- @Override
- public void computeScroll() {
- if (scroller.computeScrollOffset()) {
- scrollTo(scroller.getCurrX(), 0);
- postInvalidate();
- }
- }
编写了一个名为 scrollToScreen的方法,用于根据指定屏幕号切换到该屏幕:
Java代码:
- /**
- * 切换到指定屏
- *
- * @param whichScreen
- */
- public void scrollToScreen(int whichScreen) {
- if (getFocusedChild() != null && whichScreen != currentScreenIndex
- && getFocusedChild() == getChildAt(currentScreenIndex)) {
- getFocusedChild().clearFocus();
- }
- final int delta = whichScreen * getWidth() – getScrollX();
- scroller.startScroll(getScrollX(), 0, delta, 0, Math.abs(delta) * 2);
- invalidate();
- currentScreenIndex = whichScreen;
- }
snapToDestination方法,是处理当屏幕拖动到一个位置松手后的处理:
Java代码:
- /**
- * 根据当前x坐标位置确定切换到第几屏
- */
- private void snapToDestination() {
- scrollToScreen((getScrollX() + (getWidth() / 2)) / getWidth());
- }
然后说说手势事件的处理。 eric的实现,全部使用 onTouch事件处理,这样代码不够简明。因为需要记录很多组合手势的历史数据,这样就必须有一些状态位,一些坐标数值。
我用 GestureDetector的手势处理事件简化了这方面的处理,只在手势抬起( UP)事件处理中在 ouTouchEvent方法中做了处理。