Android 视图切换效果

 我们先来看看效果图:
8.png 

       上述截图,是手指拖动的效果,如果拖动过屏幕中点,松手后就会自动移动到第二屏。另外,如果使用轻扫手势,也可以自动移动下一屏。

         Android中的 View有两个子类, WidgetViewGroupWidget是可见的窗口组件,比如按钮, ViewGroup就是布局, ViewGroup已经提供了多个布局子类,比如 LinearLayout等。

       本例中实现了自己的 ViewGroup子类。通过覆盖 onLayout方法实现对子视图的横向排列布局:

Java代码:

  1. package eoe. result;

  2. @Override
  3. protected void onLayout(boolean changed, int left, int top, int right,
  4. int bottom) {
  5. Log.d(TAG, ">>left: " + left + " top: " + top + " right: " + right
  6. + " bottom:" + bottom);

  7. /**
  8. * 设置布局,将子视图顺序横屏排列
  9. */
  10. for (int i = 0; i < getChildCount(); i++) {
  11. View child = getChildAt(i);
  12. child.setVisibility(View.VISIBLE);
  13. child.measure(right – left, bottom – top);
  14. child.layout(0 + i * getWidth(), 0, getWidth() + i * getWidth(),
  15. getHeight());
复制代码

        通过覆盖 computeScroll方法,计算移动屏幕的位移和重新绘制屏幕:

Java代码:
  1. package eoe. result;

  2. @Override
  3. public void computeScroll() {
  4. if (scroller.computeScrollOffset()) {
  5. scrollTo(scroller.getCurrX(), 0);
  6. postInvalidate();
  7. }
  8. }
复制代码

        编写了一个名为 scrollToScreen的方法,用于根据指定屏幕号切换到该屏幕:

Java代码:
  1. /**
  2. * 切换到指定屏
  3. *
  4. * @param whichScreen
  5. */
  6. public void scrollToScreen(int whichScreen) {
  7. if (getFocusedChild() != null && whichScreen != currentScreenIndex
  8. && getFocusedChild() == getChildAt(currentScreenIndex)) {
  9. getFocusedChild().clearFocus();
  10. }

  11. final int delta = whichScreen * getWidth() – getScrollX();
  12. scroller.startScroll(getScrollX(), 0, delta, 0, Math.abs(delta) * 2);
  13. invalidate();

  14. currentScreenIndex = whichScreen;
  15. }
复制代码

         snapToDestination方法,是处理当屏幕拖动到一个位置松手后的处理:

Java代码:
  1. /**
  2. * 根据当前x坐标位置确定切换到第几屏
  3. */
  4. private void snapToDestination() {
  5. scrollToScreen((getScrollX() + (getWidth() / 2)) / getWidth());
  6. }
复制代码

       然后说说手势事件的处理。 eric的实现,全部使用 onTouch事件处理,这样代码不够简明。因为需要记录很多组合手势的历史数据,这样就必须有一些状态位,一些坐标数值。

       我用 GestureDetector的手势处理事件简化了这方面的处理,只在手势抬起( UP)事件处理中在 ouTouchEvent方法中做了处理。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值