Advertisement
Guest User

TwoDScrollViewWithBar

a guest
Jul 31st, 2012
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 39.29 KB | None | 0 0
  1. /*
  2.  * Copyright (C) 2006 The Android Open Source Project
  3.  *
  4.  * Licensed under the Apache License, Version 2.0 (the "License");
  5.  * you may not use this file except in compliance with the License.
  6.  * You may obtain a copy of the License at
  7.  *
  8.  *      http://www.apache.org/licenses/LICENSE-2.0
  9.  *
  10.  * Unless required by applicable law or agreed to in writing, software
  11.  * distributed under the License is distributed on an "AS IS" BASIS,
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13.  * See the License for the specific language governing permissions and
  14.  * limitations under the License.
  15.  */
  16. /*
  17.  * Revised 5/19/2010 by GORGES
  18.  * Now supports two-dimensional view scrolling
  19.  * http://GORGES.us
  20.  */
  21.  
  22. package us.gorges.viewaclue;
  23.  
  24. import java.util.List;
  25.  
  26. import android.content.Context;
  27. import android.graphics.Rect;
  28. import android.util.AttributeSet;
  29. import android.view.FocusFinder;
  30. import android.view.KeyEvent;
  31. import android.view.MotionEvent;
  32. import android.view.VelocityTracker;
  33. import android.view.View;
  34. import android.view.ViewConfiguration;
  35. import android.view.ViewGroup;
  36. import android.view.ViewParent;
  37. import android.view.animation.AnimationUtils;
  38. import android.widget.FrameLayout;
  39. import android.widget.LinearLayout;
  40. import android.widget.Scroller;
  41. import android.widget.TextView;
  42.  
  43. /**
  44.  * Layout container for a view hierarchy that can be scrolled by the user,
  45.  * allowing it to be larger than the physical display.  A TwoDScrollView
  46.  * is a {@link FrameLayout}, meaning you should place one child in it
  47.  * containing the entire contents to scroll; this child may itself be a layout
  48.  * manager with a complex hierarchy of objects.  A child that is often used
  49.  * is a {@link LinearLayout} in a vertical orientation, presenting a vertical
  50.  * array of top-level items that the user can scroll through.
  51.  *
  52.  * <p>The {@link TextView} class also
  53.  * takes care of its own scrolling, so does not require a TwoDScrollView, but
  54.  * using the two together is possible to achieve the effect of a text view
  55.  * within a larger container.
  56.  */
  57. public class TwoDScrollViewWithBar extends FrameLayout {
  58.  static final int ANIMATED_SCROLL_GAP = 250;
  59.  static final float MAX_SCROLL_FACTOR = 0.5f;
  60.  
  61.  private long mLastScroll;
  62.  
  63.  private final Rect mTempRect = new Rect();
  64.  private Scroller mScroller;
  65.  
  66.  /**
  67.  * Flag to indicate that we are moving focus ourselves. This is so the
  68.  * code that watches for focus changes initiated outside this TwoDScrollView
  69.  * knows that it does not have to do anything.
  70.  */
  71.  private boolean mTwoDScrollViewMovedFocus;
  72.  
  73.  /**
  74.  * Position of the last motion event.
  75.  */
  76.  private float mLastMotionY;
  77.  private float mLastMotionX;
  78.  
  79.  /**
  80.  * True when the layout has changed but the traversal has not come through yet.
  81.  * Ideally the view hierarchy would keep track of this for us.
  82.  */
  83.  private boolean mIsLayoutDirty = true;
  84.  
  85.  /**
  86.  * The child to give focus to in the event that a child has requested focus while the
  87.  * layout is dirty. This prevents the scroll from being wrong if the child has not been
  88.  * laid out before requesting focus.
  89.  */
  90.  private View mChildToScrollTo = null;
  91.  
  92.  /**
  93.  * True if the user is currently dragging this TwoDScrollView around. This is
  94.  * not the same as 'is being flinged', which can be checked by
  95.  * mScroller.isFinished() (flinging begins when the user lifts his finger).
  96.  */
  97.  private boolean mIsBeingDragged = false;
  98.  
  99.  /**
  100.  * Determines speed during touch scrolling
  101.  */
  102.  private VelocityTracker mVelocityTracker;
  103.  
  104.  /**
  105.  * Whether arrow scrolling is animated.
  106.  */
  107.  private int mTouchSlop;
  108.  private int mMinimumVelocity;
  109.  private int mMaximumVelocity;
  110.  
  111.  public TwoDScrollViewWithBar(Context context) {
  112.    super(context);
  113.    initTwoDScrollView();
  114.  }
  115.  
  116.  public TwoDScrollViewWithBar(Context context, AttributeSet attrs) {
  117.    super(context, attrs);
  118.    initTwoDScrollView();
  119.  }
  120.  
  121.  public TwoDScrollViewWithBar(Context context, AttributeSet attrs, int defStyle) {
  122.    super(context, attrs, defStyle);
  123.    initTwoDScrollView();
  124.  }
  125.  
  126.  @Override
  127.  protected float getTopFadingEdgeStrength() {
  128.    if (getChildCount() == 0) {
  129.      return 0.0f;
  130.    }
  131.    final int length = getVerticalFadingEdgeLength();
  132.    if (getScrollY() < length) {
  133.      return getScrollY() / (float) length;
  134.    }
  135.    return 1.0f;
  136.  }
  137.  
  138.  @Override
  139.  protected float getBottomFadingEdgeStrength() {
  140.    if (getChildCount() == 0) {
  141.      return 0.0f;
  142.    }
  143.    final int length = getVerticalFadingEdgeLength();
  144.    final int bottomEdge = getHeight() - getPaddingBottom();
  145.    final int span = getChildAt(0).getBottom() - getScrollY() - bottomEdge;
  146.    if (span < length) {
  147.      return span / (float) length;
  148.    }
  149.    return 1.0f;
  150.  }
  151.  
  152.  @Override
  153.  protected float getLeftFadingEdgeStrength() {
  154.    if (getChildCount() == 0) {
  155.      return 0.0f;
  156.    }
  157.    final int length = getHorizontalFadingEdgeLength();
  158.    if (getScrollX() < length) {
  159.      return getScrollX() / (float) length;
  160.    }
  161.    return 1.0f;
  162.  }
  163.  
  164.  @Override
  165.  protected float getRightFadingEdgeStrength() {
  166.    if (getChildCount() == 0) {
  167.      return 0.0f;
  168.    }
  169.    final int length = getHorizontalFadingEdgeLength();
  170.    final int rightEdge = getWidth() - getPaddingRight();
  171.    final int span = getChildAt(0).getRight() - getScrollX() - rightEdge;
  172.    if (span < length) {
  173.      return span / (float) length;
  174.    }
  175.    return 1.0f;
  176.  }
  177.  
  178.  /**
  179.  * @return The maximum amount this scroll view will scroll in response to
  180.  *   an arrow event.
  181.  */
  182.  public int getMaxScrollAmountVertical() {
  183.    return (int) (MAX_SCROLL_FACTOR * getHeight());
  184.  }
  185.  public int getMaxScrollAmountHorizontal() {
  186.    return (int) (MAX_SCROLL_FACTOR * getWidth());
  187.  }
  188.  
  189.  private void initTwoDScrollView() {
  190.    mScroller = new Scroller(getContext());
  191.    setFocusable(true);
  192.    setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);
  193.    setWillNotDraw(false);
  194.    final ViewConfiguration configuration = ViewConfiguration.get(getContext());
  195.    mTouchSlop = configuration.getScaledTouchSlop();
  196.    mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();
  197.    mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
  198.  }
  199.  
  200.  @Override
  201.  public void addView(View child) {
  202.    if (getChildCount() > 0) {
  203.      throw new IllegalStateException("TwoDScrollView can host only one direct child");
  204.    }
  205.    super.addView(child);
  206.  }
  207.  
  208.  @Override
  209.  public void addView(View child, int index) {
  210.    if (getChildCount() > 0) {
  211.      throw new IllegalStateException("TwoDScrollView can host only one direct child");
  212.    }
  213.    super.addView(child, index);
  214.  }
  215.  
  216.  @Override
  217.  public void addView(View child, ViewGroup.LayoutParams params) {
  218.    if (getChildCount() > 0) {
  219.      throw new IllegalStateException("TwoDScrollView can host only one direct child");
  220.    }
  221.    super.addView(child, params);
  222.  }
  223.  
  224.  @Override
  225.  public void addView(View child, int index, ViewGroup.LayoutParams params) {
  226.    if (getChildCount() > 0) {
  227.      throw new IllegalStateException("TwoDScrollView can host only one direct child");
  228.    }
  229.    super.addView(child, index, params);
  230.  }
  231.  
  232.  /**
  233.  * @return Returns true this TwoDScrollView can be scrolled
  234.  */
  235.  private boolean canScroll() {
  236.    View child = getChildAt(0);
  237.    if (child != null) {
  238.      int childHeight = child.getHeight();
  239.      int childWidth = child.getWidth();
  240.      return (getHeight() < childHeight + getPaddingTop() + getPaddingBottom()) ||
  241.             (getWidth() < childWidth + getPaddingLeft() + getPaddingRight());
  242.    }
  243.    return false;
  244.  }
  245.  
  246.  @Override
  247.  public boolean dispatchKeyEvent(KeyEvent event) {
  248.    // Let the focused view and/or our descendants get the key first
  249.    boolean handled = super.dispatchKeyEvent(event);
  250.    if (handled) {
  251.      return true;
  252.    }
  253.    return executeKeyEvent(event);
  254.  }
  255.  
  256.  /**
  257.  * You can call this function yourself to have the scroll view perform
  258.  * scrolling from a key event, just as if the event had been dispatched to
  259.  * it by the view hierarchy.
  260.  *
  261.  * @param event The key event to execute.
  262.  * @return Return true if the event was handled, else false.
  263.  */
  264.  public boolean executeKeyEvent(KeyEvent event) {
  265.    mTempRect.setEmpty();
  266.    if (!canScroll()) {
  267.      if (isFocused()) {
  268.        View currentFocused = findFocus();
  269.        if (currentFocused == this) currentFocused = null;
  270.        View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, View.FOCUS_DOWN);
  271.        return nextFocused != null && nextFocused != this && nextFocused.requestFocus(View.FOCUS_DOWN);
  272.      }
  273.      return false;
  274.    }
  275.    boolean handled = false;
  276.    if (event.getAction() == KeyEvent.ACTION_DOWN) {
  277.      switch (event.getKeyCode()) {
  278.        case KeyEvent.KEYCODE_DPAD_UP:
  279.          if (!event.isAltPressed()) {
  280.            handled = arrowScroll(View.FOCUS_UP, false);
  281.          } else {
  282.            handled = fullScroll(View.FOCUS_UP, false);
  283.          }
  284.          break;
  285.        case KeyEvent.KEYCODE_DPAD_DOWN:
  286.          if (!event.isAltPressed()) {
  287.            handled = arrowScroll(View.FOCUS_DOWN, false);
  288.          } else {
  289.            handled = fullScroll(View.FOCUS_DOWN, false);
  290.          }
  291.          break;
  292.        case KeyEvent.KEYCODE_DPAD_LEFT:
  293.          if (!event.isAltPressed()) {
  294.            handled = arrowScroll(View.FOCUS_UP, true);
  295.          } else {
  296.            handled = fullScroll(View.FOCUS_UP, true);
  297.          }
  298.          break;
  299.        case KeyEvent.KEYCODE_DPAD_RIGHT:
  300.          if (!event.isAltPressed()) {
  301.            handled = arrowScroll(View.FOCUS_DOWN, true);
  302.          } else {
  303.            handled = fullScroll(View.FOCUS_DOWN, true);
  304.          }
  305.          break;
  306.      }
  307.    }
  308.    return handled;
  309.  }
  310.  
  311.  @Override
  312.  public boolean onInterceptTouchEvent(MotionEvent ev) {
  313.    /*
  314.    * This method JUST determines whether we want to intercept the motion.
  315.    * If we return true, onMotionEvent will be called and we do the actual
  316.    * scrolling there.
  317.    *
  318.    * Shortcut the most recurring case: the user is in the dragging
  319.    * state and he is moving his finger.  We want to intercept this
  320.    * motion.
  321.    */
  322.    final int action = ev.getAction();
  323.    if ((action == MotionEvent.ACTION_MOVE) && (mIsBeingDragged)) {
  324.      return true;
  325.    }
  326.    if (!canScroll()) {
  327.      mIsBeingDragged = false;
  328.      return false;
  329.    }
  330.    final float y = ev.getY();
  331.    final float x = ev.getX();
  332.    switch (action) {
  333.      case MotionEvent.ACTION_MOVE:
  334.        /*
  335.        * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
  336.        * whether the user has moved far enough from his original down touch.
  337.        */
  338.        /*
  339.        * Locally do absolute value. mLastMotionY is set to the y value
  340.        * of the down event.
  341.        */
  342.        final int yDiff = (int) Math.abs(y - mLastMotionY);
  343.        final int xDiff = (int) Math.abs(x - mLastMotionX);
  344.        if (yDiff > mTouchSlop || xDiff > mTouchSlop) {
  345.          mIsBeingDragged = true;
  346.        }
  347.        break;
  348.  
  349.      case MotionEvent.ACTION_DOWN:
  350.        /* Remember location of down touch */
  351.        mLastMotionY = y;
  352.        mLastMotionX = x;
  353.  
  354.        /*
  355.        * If being flinged and user touches the screen, initiate drag;
  356.        * otherwise don't.  mScroller.isFinished should be false when
  357.        * being flinged.
  358.        */
  359.        mIsBeingDragged = !mScroller.isFinished();
  360.        break;
  361.  
  362.      case MotionEvent.ACTION_CANCEL:
  363.      case MotionEvent.ACTION_UP:
  364.        /* Release the drag */
  365.        mIsBeingDragged = false;
  366.        break;
  367.    }
  368.  
  369.    /*
  370.    * The only time we want to intercept motion events is if we are in the
  371.    * drag mode.
  372.    */
  373.    return mIsBeingDragged;
  374.  }
  375.  
  376.  @Override
  377.  public boolean onTouchEvent(MotionEvent ev) {
  378.  
  379.    if (ev.getAction() == MotionEvent.ACTION_DOWN && ev.getEdgeFlags() != 0) {
  380.      // Don't handle edge touches immediately -- they may actually belong to one of our
  381.      // descendants.
  382.      return false;
  383.    }
  384.  
  385.    if (!canScroll()) {
  386.      return false;
  387.    }
  388.  
  389.    if (mVelocityTracker == null) {
  390.      mVelocityTracker = VelocityTracker.obtain();
  391.    }
  392.    mVelocityTracker.addMovement(ev);
  393.  
  394.    final int action = ev.getAction();
  395.    final float y = ev.getY();
  396.    final float x = ev.getX();
  397.  
  398.    switch (action) {
  399.      case MotionEvent.ACTION_DOWN:
  400.        /*
  401.        * If being flinged and user touches, stop the fling. isFinished
  402.        * will be false if being flinged.
  403.        */
  404.        if (!mScroller.isFinished()) {
  405.          mScroller.abortAnimation();
  406.        }
  407.  
  408.        // Remember where the motion event started
  409.        mLastMotionY = y;
  410.        mLastMotionX = x;
  411.        break;
  412.      case MotionEvent.ACTION_MOVE:
  413.        // Scroll to follow the motion event
  414.        int deltaX = (int) (mLastMotionX - x);
  415.        int deltaY = (int) (mLastMotionY - y);
  416.        mLastMotionX = x;
  417.        mLastMotionY = y;
  418.  
  419.        if (deltaX < 0) {
  420.          if (getScrollX() < 0) {
  421.            deltaX = 0;
  422.          }
  423.        } else if (deltaX > 0) {
  424.          final int rightEdge = getWidth() - getPaddingRight();
  425.          final int availableToScroll = getChildAt(0).getRight() - getScrollX() - rightEdge;
  426.          if (availableToScroll > 0) {
  427.            deltaX = Math.min(availableToScroll, deltaX);
  428.          } else {
  429.            deltaX = 0;
  430.          }
  431.        }
  432.        if (deltaY < 0) {
  433.          if (getScrollY() < 0) {
  434.            deltaY = 0;
  435.          }
  436.        } else if (deltaY > 0) {
  437.          final int bottomEdge = getHeight() - getPaddingBottom();
  438.          final int availableToScroll = getChildAt(0).getBottom() - getScrollY() - bottomEdge;
  439.          if (availableToScroll > 0) {
  440.            deltaY = Math.min(availableToScroll, deltaY);
  441.          } else {
  442.            deltaY = 0;
  443.          }
  444.        }
  445.        if (deltaY != 0 || deltaX != 0)
  446.          scrollBy(deltaX, deltaY);
  447.        break;
  448.      case MotionEvent.ACTION_UP:
  449.          final VelocityTracker velocityTracker = mVelocityTracker;
  450.          velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
  451.          int initialXVelocity = (int) velocityTracker.getXVelocity();
  452.          int initialYVelocity = (int) velocityTracker.getYVelocity();
  453.          if ((Math.abs(initialXVelocity) + Math.abs(initialYVelocity) > mMinimumVelocity) && getChildCount() > 0) {
  454.            fling(-initialXVelocity, -initialYVelocity);
  455.          }
  456.          if (mVelocityTracker != null) {
  457.            mVelocityTracker.recycle();
  458.            mVelocityTracker = null;
  459.          }
  460.    }
  461.    return true;
  462.  }
  463.  
  464.  /**
  465.   * Finds the next focusable component that fits in this View's bounds
  466.   * (excluding fading edges) pretending that this View's top is located at
  467.   * the parameter top.
  468.   *
  469.   * @param topFocus           look for a candidate is the one at the top of the bounds
  470.   *                           if topFocus is true, or at the bottom of the bounds if topFocus is
  471.   *                           false
  472.   * @param top                the top offset of the bounds in which a focusable must be
  473.   *                           found (the fading edge is assumed to start at this position)
  474.   * @param preferredFocusable the View that has highest priority and will be
  475.   *                           returned if it is within my bounds (null is valid)
  476.   * @return the next focusable component in the bounds or null if none can be
  477.   *         found
  478.   */
  479.  private View findFocusableViewInMyBounds(final boolean topFocus, final int top, final boolean leftFocus, final int left, View preferredFocusable) {
  480.    /*
  481.    * The fading edge's transparent side should be considered for focus
  482.    * since it's mostly visible, so we divide the actual fading edge length
  483.    * by 2.
  484.    */
  485.    final int verticalFadingEdgeLength = getVerticalFadingEdgeLength() / 2;
  486.    final int topWithoutFadingEdge = top + verticalFadingEdgeLength;
  487.    final int bottomWithoutFadingEdge = top + getHeight() - verticalFadingEdgeLength;
  488.    final int horizontalFadingEdgeLength = getHorizontalFadingEdgeLength() / 2;
  489.    final int leftWithoutFadingEdge = left + horizontalFadingEdgeLength;
  490.    final int rightWithoutFadingEdge = left + getWidth() - horizontalFadingEdgeLength;
  491.  
  492.    if ((preferredFocusable != null)
  493.      && (preferredFocusable.getTop() < bottomWithoutFadingEdge)
  494.      && (preferredFocusable.getBottom() > topWithoutFadingEdge)
  495.      && (preferredFocusable.getLeft() < rightWithoutFadingEdge)
  496.      && (preferredFocusable.getRight() > leftWithoutFadingEdge)) {
  497.      return preferredFocusable;
  498.    }
  499.    return findFocusableViewInBounds(topFocus, topWithoutFadingEdge, bottomWithoutFadingEdge, leftFocus, leftWithoutFadingEdge, rightWithoutFadingEdge);
  500.  }
  501.  
  502.  /**
  503.  * Finds the next focusable component that fits in the specified bounds.
  504.  * </p>
  505.  
  506.  *
  507.  * @param topFocus look for a candidate is the one at the top of the bounds
  508.  *                 if topFocus is true, or at the bottom of the bounds if topFocus is
  509.  *                 false
  510.  * @param top      the top offset of the bounds in which a focusable must be
  511.  *                 found
  512.  * @param bottom   the bottom offset of the bounds in which a focusable must
  513.  *                 be found
  514.  * @return the next focusable component in the bounds or null if none can
  515.  *         be found
  516.  */
  517.  private View findFocusableViewInBounds(boolean topFocus, int top, int bottom, boolean leftFocus, int left, int right) {
  518.    List<View> focusables = getFocusables(View.FOCUS_FORWARD);
  519.    View focusCandidate = null;
  520.  
  521.    /*
  522.    * A fully contained focusable is one where its top is below the bound's
  523.    * top, and its bottom is above the bound's bottom. A partially
  524.    * contained focusable is one where some part of it is within the
  525.    * bounds, but it also has some part that is not within bounds.  A fully contained
  526.    * focusable is preferred to a partially contained focusable.
  527.    */
  528.    boolean foundFullyContainedFocusable = false;
  529.  
  530.    int count = focusables.size();
  531.    for (int i = 0; i < count; i++) {
  532.      View view = focusables.get(i);
  533.      int viewTop = view.getTop();
  534.      int viewBottom = view.getBottom();
  535.      int viewLeft = view.getLeft();
  536.      int viewRight = view.getRight();
  537.  
  538.      if (top < viewBottom && viewTop < bottom && left < viewRight && viewLeft < right) {
  539.        /*
  540.        * the focusable is in the target area, it is a candidate for
  541.        * focusing
  542.        */
  543.        final boolean viewIsFullyContained = (top < viewTop) && (viewBottom < bottom) && (left < viewLeft) && (viewRight < right);
  544.        if (focusCandidate == null) {
  545.          /* No candidate, take this one */
  546.          focusCandidate = view;
  547.          foundFullyContainedFocusable = viewIsFullyContained;
  548.        } else {
  549.          final boolean viewIsCloserToVerticalBoundary =
  550.            (topFocus && viewTop < focusCandidate.getTop()) ||
  551.            (!topFocus && viewBottom > focusCandidate.getBottom());
  552.          final boolean viewIsCloserToHorizontalBoundary =
  553.            (leftFocus && viewLeft < focusCandidate.getLeft()) ||
  554.            (!leftFocus && viewRight > focusCandidate.getRight());
  555.          if (foundFullyContainedFocusable) {
  556.            if (viewIsFullyContained && viewIsCloserToVerticalBoundary && viewIsCloserToHorizontalBoundary) {
  557.              /*
  558.               * We're dealing with only fully contained views, so
  559.               * it has to be closer to the boundary to beat our
  560.               * candidate
  561.               */
  562.              focusCandidate = view;
  563.            }
  564.          } else {
  565.            if (viewIsFullyContained) {
  566.              /* Any fully contained view beats a partially contained view */
  567.              focusCandidate = view;
  568.              foundFullyContainedFocusable = true;
  569.            } else if (viewIsCloserToVerticalBoundary && viewIsCloserToHorizontalBoundary) {
  570.              /*
  571.               * Partially contained view beats another partially
  572.               * contained view if it's closer
  573.               */
  574.              focusCandidate = view;
  575.            }
  576.          }
  577.        }
  578.      }
  579.    }
  580.    return focusCandidate;
  581.  }
  582.  
  583.  /**
  584.   * <p>Handles scrolling in response to a "home/end" shortcut press. This
  585.   * method will scroll the view to the top or bottom and give the focus
  586.   * to the topmost/bottommost component in the new visible area. If no
  587.   * component is a good candidate for focus, this scrollview reclaims the
  588.   * focus.</p>
  589.  
  590.   *
  591.   * @param direction the scroll direction: {@link android.view.View#FOCUS_UP}
  592.   *                  to go the top of the view or
  593.   *                  {@link android.view.View#FOCUS_DOWN} to go the bottom
  594.   * @return true if the key event is consumed by this method, false otherwise
  595.   */
  596.  public boolean fullScroll(int direction, boolean horizontal) {
  597.    if (!horizontal) {
  598.      boolean down = direction == View.FOCUS_DOWN;
  599.      int height = getHeight();
  600.      mTempRect.top = 0;
  601.      mTempRect.bottom = height;
  602.      if (down) {
  603.        int count = getChildCount();
  604.        if (count > 0) {
  605.          View view = getChildAt(count - 1);
  606.          mTempRect.bottom = view.getBottom();
  607.          mTempRect.top = mTempRect.bottom - height;
  608.        }
  609.      }
  610.      return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom, 0, 0, 0);
  611.    } else {
  612.      boolean right = direction == View.FOCUS_DOWN;
  613.      int width = getWidth();
  614.      mTempRect.left = 0;
  615.      mTempRect.right = width;
  616.      if (right) {
  617.        int count = getChildCount();
  618.        if (count > 0) {
  619.          View view = getChildAt(count - 1);
  620.          mTempRect.right = view.getBottom();
  621.          mTempRect.left = mTempRect.right - width;
  622.        }
  623.      }
  624.      return scrollAndFocus(0, 0, 0, direction, mTempRect.top, mTempRect.bottom);
  625.    }
  626.  }
  627.  
  628.  /**
  629.   * <p>Scrolls the view to make the area defined by <code>top</code> and
  630.   * <code>bottom</code> visible. This method attempts to give the focus
  631.   * to a component visible in this area. If no component can be focused in
  632.   * the new visible area, the focus is reclaimed by this scrollview.</p>
  633.  
  634.   *
  635.   * @param direction the scroll direction: {@link android.view.View#FOCUS_UP}
  636.   *                  to go upward
  637.   *                  {@link android.view.View#FOCUS_DOWN} to downward
  638.   * @param top       the top offset of the new area to be made visible
  639.   * @param bottom    the bottom offset of the new area to be made visible
  640.   * @return true if the key event is consumed by this method, false otherwise
  641.   */
  642.  private boolean scrollAndFocus(int directionY, int top, int bottom, int directionX, int left, int right) {
  643.    boolean handled = true;
  644.    int height = getHeight();
  645.    int containerTop = getScrollY();
  646.    int containerBottom = containerTop + height;
  647.    boolean up = directionY == View.FOCUS_UP;
  648.    int width = getWidth();
  649.    int containerLeft = getScrollX();
  650.    int containerRight = containerLeft + width;
  651.    boolean leftwards = directionX == View.FOCUS_UP;
  652.    View newFocused = findFocusableViewInBounds(up, top, bottom, leftwards, left, right);
  653.    if (newFocused == null) {
  654.      newFocused = this;
  655.    }
  656.    if ((top >= containerTop && bottom <= containerBottom) || (left >= containerLeft && right <= containerRight)) {
  657.      handled = false;
  658.    } else {
  659.      int deltaY = up ? (top - containerTop) : (bottom - containerBottom);
  660.      int deltaX = leftwards ? (left - containerLeft) : (right - containerRight);
  661.      doScroll(deltaX, deltaY);
  662.    }
  663.    if (newFocused != findFocus() && newFocused.requestFocus(directionY)) {
  664.      mTwoDScrollViewMovedFocus = true;
  665.      mTwoDScrollViewMovedFocus = false;
  666.    }
  667.    return handled;
  668.  }
  669.  
  670.  /**
  671.   * Handle scrolling in response to an up or down arrow click.
  672.   *
  673.   * @param direction The direction corresponding to the arrow key that was
  674.   *                  pressed
  675.   * @return True if we consumed the event, false otherwise
  676.   */
  677.  public boolean arrowScroll(int direction, boolean horizontal) {
  678.    View currentFocused = findFocus();
  679.    if (currentFocused == this) currentFocused = null;
  680.    View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction);
  681.    final int maxJump = horizontal ? getMaxScrollAmountHorizontal() : getMaxScrollAmountVertical();
  682.  
  683.    if (!horizontal) {
  684.      if (nextFocused != null) {
  685.        nextFocused.getDrawingRect(mTempRect);
  686.        offsetDescendantRectToMyCoords(nextFocused, mTempRect);
  687.        int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
  688.        doScroll(0, scrollDelta);
  689.        nextFocused.requestFocus(direction);
  690.      } else {
  691.        // no new focus
  692.        int scrollDelta = maxJump;
  693.        if (direction == View.FOCUS_UP && getScrollY() < scrollDelta) {
  694.          scrollDelta = getScrollY();
  695.        } else if (direction == View.FOCUS_DOWN) {
  696.          if (getChildCount() > 0) {
  697.            int daBottom = getChildAt(0).getBottom();
  698.            int screenBottom = getScrollY() + getHeight();
  699.            if (daBottom - screenBottom < maxJump) {
  700.              scrollDelta = daBottom - screenBottom;
  701.            }
  702.          }
  703.        }
  704.        if (scrollDelta == 0) {
  705.          return false;
  706.        }
  707.        doScroll(0, direction == View.FOCUS_DOWN ? scrollDelta : -scrollDelta);
  708.      }
  709.    } else {
  710.      if (nextFocused != null) {
  711.        nextFocused.getDrawingRect(mTempRect);
  712.        offsetDescendantRectToMyCoords(nextFocused, mTempRect);
  713.        int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
  714.        doScroll(scrollDelta, 0);
  715.        nextFocused.requestFocus(direction);
  716.      } else {
  717.        // no new focus
  718.        int scrollDelta = maxJump;
  719.        if (direction == View.FOCUS_UP && getScrollY() < scrollDelta) {
  720.          scrollDelta = getScrollY();
  721.        } else if (direction == View.FOCUS_DOWN) {
  722.          if (getChildCount() > 0) {
  723.            int daBottom = getChildAt(0).getBottom();
  724.            int screenBottom = getScrollY() + getHeight();
  725.            if (daBottom - screenBottom < maxJump) {
  726.              scrollDelta = daBottom - screenBottom;
  727.            }
  728.          }
  729.        }
  730.        if (scrollDelta == 0) {
  731.          return false;
  732.        }
  733.        doScroll(direction == View.FOCUS_DOWN ? scrollDelta : -scrollDelta, 0);
  734.      }
  735.    }
  736.    return true;
  737.  }
  738.  
  739.  /**
  740.   * Smooth scroll by a Y delta
  741.   *
  742.   * @param delta the number of pixels to scroll by on the Y axis
  743.   */
  744.  private void doScroll(int deltaX, int deltaY) {
  745.    if (deltaX != 0 || deltaY != 0) {
  746.      smoothScrollBy(deltaX, deltaY);
  747.    }
  748.  }
  749.  
  750.  /**
  751.   * Like {@link View#scrollBy}, but scroll smoothly instead of immediately.
  752.   *
  753.   * @param dx the number of pixels to scroll by on the X axis
  754.   * @param dy the number of pixels to scroll by on the Y axis
  755.   */
  756.  public final void smoothScrollBy(int dx, int dy) {
  757.    long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll;
  758.    if (duration > ANIMATED_SCROLL_GAP) {
  759.      mScroller.startScroll(getScrollX(), getScrollY(), dx, dy);
  760.      awakenScrollBars(mScroller.getDuration());
  761.      invalidate();
  762.    } else {
  763.      if (!mScroller.isFinished()) {
  764.        mScroller.abortAnimation();
  765.      }
  766.      scrollBy(dx, dy);
  767.    }
  768.    mLastScroll = AnimationUtils.currentAnimationTimeMillis();
  769.  }
  770.  
  771.  /**
  772.   * Like {@link #scrollTo}, but scroll smoothly instead of immediately.
  773.   *
  774.   * @param x the position where to scroll on the X axis
  775.   * @param y the position where to scroll on the Y axis
  776.   */
  777.  public final void smoothScrollTo(int x, int y) {
  778.    smoothScrollBy(x - getScrollX(), y - getScrollY());
  779.  }
  780.  
  781.  /**
  782.   * <p>The scroll range of a scroll view is the overall height of all of its
  783.   * children.</p>
  784.  
  785.   */
  786.  @Override
  787.  protected int computeVerticalScrollRange() {
  788.    int count = getChildCount();
  789.    return count == 0 ? getHeight() : (getChildAt(0)).getBottom();
  790.  }
  791.  @Override
  792.  protected int computeHorizontalScrollRange() {
  793.    int count = getChildCount();
  794.    return count == 0 ? getWidth() : (getChildAt(0)).getRight();
  795.  }
  796.  
  797.  @Override
  798.  protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) {
  799.    ViewGroup.LayoutParams lp = child.getLayoutParams();
  800.    int childWidthMeasureSpec;
  801.    int childHeightMeasureSpec;
  802.  
  803.    childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, getPaddingLeft() + getPaddingRight(), lp.width);
  804.    childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
  805.  
  806.    child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
  807.  }
  808.  
  809.  @Override
  810.  protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed) {
  811.    final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
  812.    final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
  813.    getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin + widthUsed, lp.width);
  814.    final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(lp.topMargin + lp.bottomMargin, MeasureSpec.UNSPECIFIED);
  815.  
  816.    child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
  817.  }
  818.  
  819.  @Override
  820.  public void computeScroll() {
  821.    if (mScroller.computeScrollOffset()) {
  822.      // This is called at drawing time by ViewGroup.  We don't want to
  823.      // re-show the scrollbars at this point, which scrollTo will do,
  824.      // so we replicate most of scrollTo here.
  825.      //
  826.      //         It's a little odd to call onScrollChanged from inside the drawing.
  827.      //
  828.      //         It is, except when you remember that computeScroll() is used to
  829.      //         animate scrolling. So unless we want to defer the onScrollChanged()
  830.      //         until the end of the animated scrolling, we don't really have a
  831.      //         choice here.
  832.      //
  833.      //         I agree.  The alternative, which I think would be worse, is to post
  834.      //         something and tell the subclasses later.  This is bad because there
  835.      //         will be a window where mScrollX/Y is different from what the app
  836.      //         thinks it is.
  837.      //
  838.      int oldX = getScrollX();
  839.      int oldY = getScrollY();
  840.      int x = mScroller.getCurrX();
  841.      int y = mScroller.getCurrY();
  842.      if (getChildCount() > 0) {
  843.        View child = getChildAt(0);
  844.        scrollTo(clamp(x, getWidth() - getPaddingRight() - getPaddingLeft(), child.getWidth()),
  845.        clamp(y, getHeight() - getPaddingBottom() - getPaddingTop(), child.getHeight()));
  846.      } else {
  847.        scrollTo(x, y);
  848.      }
  849.      if (oldX != getScrollX() || oldY != getScrollY()) {
  850.        onScrollChanged(getScrollX(), getScrollY(), oldX, oldY);
  851.      }
  852.  
  853.      // Keep on drawing until the animation has finished.
  854.      postInvalidate();
  855.    }
  856.  }
  857.  
  858.  /**
  859.   * Scrolls the view to the given child.
  860.   *
  861.   * @param child the View to scroll to
  862.   */
  863.  private void scrollToChild(View child) {
  864.    child.getDrawingRect(mTempRect);
  865.    /* Offset from child's local coordinates to TwoDScrollView coordinates */
  866.    offsetDescendantRectToMyCoords(child, mTempRect);
  867.    int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
  868.    if (scrollDelta != 0) {
  869.      scrollBy(0, scrollDelta);
  870.    }
  871.  }
  872.  
  873.  /**
  874.   * If rect is off screen, scroll just enough to get it (or at least the
  875.   * first screen size chunk of it) on screen.
  876.   *
  877.   * @param rect      The rectangle.
  878.   * @param immediate True to scroll immediately without animation
  879.   * @return true if scrolling was performed
  880.   */
  881.  private boolean scrollToChildRect(Rect rect, boolean immediate) {
  882.    final int delta = computeScrollDeltaToGetChildRectOnScreen(rect);
  883.    final boolean scroll = delta != 0;
  884.    if (scroll) {
  885.      if (immediate) {
  886.        scrollBy(0, delta);
  887.      } else {
  888.        smoothScrollBy(0, delta);
  889.      }
  890.    }
  891.    return scroll;
  892.  }
  893.  
  894.  /**
  895.   * Compute the amount to scroll in the Y direction in order to get
  896.   * a rectangle completely on the screen (or, if taller than the screen,
  897.   * at least the first screen size chunk of it).
  898.   *
  899.   * @param rect The rect.
  900.   * @return The scroll delta.
  901.   */
  902.  protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) {
  903.    if (getChildCount() == 0) return 0;
  904.    int height = getHeight();
  905.    int screenTop = getScrollY();
  906.    int screenBottom = screenTop + height;
  907.    int fadingEdge = getVerticalFadingEdgeLength();
  908.    // leave room for top fading edge as long as rect isn't at very top
  909.    if (rect.top > 0) {
  910.      screenTop += fadingEdge;
  911.    }
  912.  
  913.    // leave room for bottom fading edge as long as rect isn't at very bottom
  914.    if (rect.bottom < getChildAt(0).getHeight()) {
  915.      screenBottom -= fadingEdge;
  916.    }
  917.    int scrollYDelta = 0;
  918.    if (rect.bottom > screenBottom && rect.top > screenTop) {
  919.      // need to move down to get it in view: move down just enough so
  920.      // that the entire rectangle is in view (or at least the first
  921.      // screen size chunk).
  922.      if (rect.height() > height) {
  923.        // just enough to get screen size chunk on
  924.        scrollYDelta += (rect.top - screenTop);
  925.      } else {
  926.        // get entire rect at bottom of screen
  927.        scrollYDelta += (rect.bottom - screenBottom);
  928.      }
  929.  
  930.      // make sure we aren't scrolling beyond the end of our content
  931.      int bottom = getChildAt(0).getBottom();
  932.      int distanceToBottom = bottom - screenBottom;
  933.      scrollYDelta = Math.min(scrollYDelta, distanceToBottom);
  934.  
  935.    } else if (rect.top < screenTop && rect.bottom < screenBottom) {
  936.      // need to move up to get it in view: move up just enough so that
  937.      // entire rectangle is in view (or at least the first screen
  938.      // size chunk of it).
  939.  
  940.      if (rect.height() > height) {
  941.        // screen size chunk
  942.        scrollYDelta -= (screenBottom - rect.bottom);
  943.      } else {
  944.        // entire rect at top
  945.        scrollYDelta -= (screenTop - rect.top);
  946.      }
  947.  
  948.      // make sure we aren't scrolling any further than the top our content
  949.      scrollYDelta = Math.max(scrollYDelta, -getScrollY());
  950.    }
  951.    return scrollYDelta;
  952.  }
  953.  
  954.  @Override
  955.  public void requestChildFocus(View child, View focused) {
  956.    if (!mTwoDScrollViewMovedFocus) {
  957.      if (!mIsLayoutDirty) {
  958.        scrollToChild(focused);
  959.      } else {
  960.        // The child may not be laid out yet, we can't compute the scroll yet
  961.        mChildToScrollTo = focused;
  962.      }
  963.    }
  964.    super.requestChildFocus(child, focused);
  965.  }
  966.  
  967.  /**
  968.   * When looking for focus in children of a scroll view, need to be a little
  969.   * more careful not to give focus to something that is scrolled off screen.
  970.   *
  971.   * This is more expensive than the default {@link android.view.ViewGroup}
  972.   * implementation, otherwise this behavior might have been made the default.
  973.   */
  974.  @Override
  975.  protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
  976.    // convert from forward / backward notation to up / down / left / right
  977.    // (ugh).
  978.    if (direction == View.FOCUS_FORWARD) {
  979.      direction = View.FOCUS_DOWN;
  980.    } else if (direction == View.FOCUS_BACKWARD) {
  981.      direction = View.FOCUS_UP;
  982.    }
  983.  
  984.    final View nextFocus = previouslyFocusedRect == null ?
  985.    FocusFinder.getInstance().findNextFocus(this, null, direction) :
  986.    FocusFinder.getInstance().findNextFocusFromRect(this,
  987.    previouslyFocusedRect, direction);
  988.  
  989.    if (nextFocus == null) {
  990.      return false;
  991.    }
  992.  
  993.    return nextFocus.requestFocus(direction, previouslyFocusedRect);
  994.  }
  995.  
  996.  @Override
  997.  public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
  998.    // offset into coordinate space of this scroll view
  999.    rectangle.offset(child.getLeft() - child.getScrollX(), child.getTop() - child.getScrollY());
  1000.    return scrollToChildRect(rectangle, immediate);
  1001.  }
  1002.  
  1003.  @Override
  1004.  public void requestLayout() {
  1005.    mIsLayoutDirty = true;
  1006.    super.requestLayout();
  1007.  }
  1008.  
  1009.  @Override
  1010.  protected void onLayout(boolean changed, int l, int t, int r, int b) {
  1011.    super.onLayout(changed, l, t, r, b);
  1012.    mIsLayoutDirty = false;
  1013.    // Give a child focus if it needs it
  1014.    if (mChildToScrollTo != null && isViewDescendantOf(mChildToScrollTo, this)) {
  1015.      scrollToChild(mChildToScrollTo);
  1016.    }
  1017.    mChildToScrollTo = null;
  1018.  
  1019.    // Calling this with the present values causes it to re-clam them
  1020.    scrollTo(getScrollX(), getScrollY());
  1021.  }
  1022.  
  1023.  @Override
  1024.  protected void onSizeChanged(int w, int h, int oldw, int oldh) {
  1025.    super.onSizeChanged(w, h, oldw, oldh);
  1026.  
  1027.    View currentFocused = findFocus();
  1028.    if (null == currentFocused || this == currentFocused)
  1029.      return;
  1030.  
  1031.    // If the currently-focused view was visible on the screen when the
  1032.    // screen was at the old height, then scroll the screen to make that
  1033.    // view visible with the new screen height.
  1034.    currentFocused.getDrawingRect(mTempRect);
  1035.    offsetDescendantRectToMyCoords(currentFocused, mTempRect);
  1036.    int scrollDeltaX = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
  1037.    int scrollDeltaY = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
  1038.    doScroll(scrollDeltaX, scrollDeltaY);
  1039.  }
  1040.  
  1041.  /**
  1042.   * Return true if child is an descendant of parent, (or equal to the parent).
  1043.   */
  1044.  private boolean isViewDescendantOf(View child, View parent) {
  1045.    if (child == parent) {
  1046.      return true;
  1047.    }
  1048.  
  1049.    final ViewParent theParent = child.getParent();
  1050.    return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
  1051.  }
  1052.  
  1053.  /**
  1054.   * Fling the scroll view
  1055.   *
  1056.   * @param velocityY The initial velocity in the Y direction. Positive
  1057.   *                  numbers mean that the finger/curor is moving down the screen,
  1058.   *                  which means we want to scroll towards the top.
  1059.   */
  1060.  public void fling(int velocityX, int velocityY) {
  1061.    if (getChildCount() > 0) {
  1062.      int height = getHeight() - getPaddingBottom() - getPaddingTop();
  1063.      int bottom = getChildAt(0).getHeight();
  1064.      int width = getWidth() - getPaddingRight() - getPaddingLeft();
  1065.      int right = getChildAt(0).getWidth();
  1066.  
  1067.      mScroller.fling(getScrollX(), getScrollY(), velocityX, velocityY, 0, right - width, 0, bottom - height);
  1068.  
  1069.      final boolean movingDown = velocityY > 0;
  1070.      final boolean movingRight = velocityX > 0;
  1071.  
  1072.      View newFocused = findFocusableViewInMyBounds(movingRight, mScroller.getFinalX(), movingDown, mScroller.getFinalY(), findFocus());
  1073.      if (newFocused == null) {
  1074.        newFocused = this;
  1075.      }
  1076.  
  1077.      if (newFocused != findFocus() && newFocused.requestFocus(movingDown ? View.FOCUS_DOWN : View.FOCUS_UP)) {
  1078.        mTwoDScrollViewMovedFocus = true;
  1079.        mTwoDScrollViewMovedFocus = false;
  1080.      }
  1081.  
  1082.      awakenScrollBars(mScroller.getDuration());
  1083.      invalidate();
  1084.    }
  1085.  }
  1086.  
  1087.  /**
  1088.   * {@inheritDoc}
  1089.   *
  1090.   * <p>This version also clamps the scrolling to the bounds of our child.
  1091.   */
  1092.  public void scrollTo(int x, int y) {
  1093.    // we rely on the fact the View.scrollBy calls scrollTo.
  1094.    if (getChildCount() > 0) {
  1095.      View child = getChildAt(0);
  1096.      x = clamp(x, getWidth() - getPaddingRight() - getPaddingLeft(), child.getWidth());
  1097.      y = clamp(y, getHeight() - getPaddingBottom() - getPaddingTop(), child.getHeight());
  1098.      if (x != getScrollX() || y != getScrollY()) {
  1099.        super.scrollTo(x, y);
  1100.      }
  1101.    }
  1102.  }
  1103.  
  1104.  private int clamp(int n, int my, int child) {
  1105.    if (my >= child || n < 0) {
  1106.      /* my >= child is this case:
  1107.       *                    |--------------- me ---------------|
  1108.       *     |------ child ------|
  1109.       * or
  1110.       *     |--------------- me ---------------|
  1111.       *            |------ child ------|
  1112.       * or
  1113.       *     |--------------- me ---------------|
  1114.       *                                  |------ child ------|
  1115.       *
  1116.       * n < 0 is this case:
  1117.       *     |------ me ------|
  1118.       *                    |-------- child --------|
  1119.       *     |-- mScrollX --|
  1120.       */
  1121.      return 0;
  1122.    }
  1123.    if ((my+n) > child) {
  1124.      /* this case:
  1125.       *                    |------ me ------|
  1126.       *     |------ child ------|
  1127.       *     |-- mScrollX --|
  1128.       */
  1129.      return child-my;
  1130.    }
  1131.    return n;
  1132.  }
  1133. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement