阅读286 返回首页    go 阿里云 go 技术社区[云栖]


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方法中做了处理。

最后更新:2017-04-02 06:51:48

  上一篇:go android多任务同时下载
  下一篇:go 【usaco】 checker