Guest User

Android: RealViewSwitcher, a nice UI component for flippable views

a guest
Dec 15th, 2010
1,077
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 11.36 KB | None | 0 0
  1. /*
  2.  * Copyright (C) 2010 Marc Reichelt
  3.  *
  4.  * Work derived from Workspace.java of the Launcher application
  5.  *  see http://android.git.kernel.org/?p=platform/packages/apps/Launcher.git
  6.  *
  7.  * Licensed under the Apache License, Version 2.0 (the "License");
  8.  * you may not use this file except in compliance with the License.
  9.  * You may obtain a copy of the License at
  10.  *
  11.  *      http://www.apache.org/licenses/LICENSE-2.0
  12.  *
  13.  * Unless required by applicable law or agreed to in writing, software
  14.  * distributed under the License is distributed on an "AS IS" BASIS,
  15.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16.  * See the License for the specific language governing permissions and
  17.  * limitations under the License.
  18.  */
  19. package de.marcreichelt.android;
  20.  
  21. import android.content.Context;
  22. import android.util.AttributeSet;
  23. import android.util.Log;
  24. import android.view.MotionEvent;
  25. import android.view.VelocityTracker;
  26. import android.view.View;
  27. import android.view.ViewConfiguration;
  28. import android.view.ViewGroup;
  29. import android.widget.Scroller;
  30.  
  31. /**
  32.  * RealViewSwitcher allows users to switch between multiple screens (layouts) in the same way as the Android home screen (Launcher application).
  33.  * <p>
  34.  * You can add and remove views using the normal methods {@link ViewGroup#addView(View)}, {@link ViewGroup#removeView(View)} etc. You may want to listen for updates by calling {@link RealViewSwitcher#setOnScreenSwitchListener(OnScreenSwitchListener)}
  35.  * in order to perform operations once a new screen has been selected.
  36.  *
  37.  * @author Marc Reichelt, <a href="http://www.marcreichelt.de/">http://www.marcreichelt.de/</a>
  38.  * @version 0.1.0
  39.  */
  40. public class RealViewSwitcher extends ViewGroup {
  41.  
  42.     /** Logging on / off. */
  43.     private static final boolean L = true;
  44.     private static final String TAG = RealViewSwitcher.class.getSimpleName();
  45.  
  46.     // TODO: This class does the basic stuff right now, but it would be cool to have certain things implemented,
  47.     // e.g. using an adapter for getting views instead of setting them directly, memory management and the
  48.     // possibility of scrolling vertically instead of horizontally. If you have ideas or patches, please visit
  49.     // my website and drop me a mail. :-)
  50.  
  51.     /**
  52.      * Listener for the event that the RealViewSwitcher switches to a new view.
  53.      */
  54.     public static interface OnScreenSwitchListener {
  55.  
  56.         /**
  57.          * Notifies listeners about the new screen. Runs after the animation completed.
  58.          *
  59.          * @param screen The new screen index.
  60.          */
  61.         void onScreenSwitched(int screen);
  62.  
  63.     }
  64.  
  65.     private static final int SNAP_VELOCITY = 1000;
  66.     private static final int INVALID_SCREEN = -1;
  67.  
  68.     private Scroller mScroller;
  69.     private VelocityTracker mVelocityTracker;
  70.  
  71.     private final static int TOUCH_STATE_REST = 0;
  72.     private final static int TOUCH_STATE_SCROLLING = 1;
  73.  
  74.     private int mTouchState = TOUCH_STATE_REST;
  75.  
  76.     private float mLastMotionX;
  77.     private float mLastMotionY;
  78.     private int mTouchSlop;
  79.     /** Allow long press? FIXME: not tested yet */
  80.     private boolean mAllowLongPress = false;
  81.     private int mMaximumVelocity;
  82.     private int mCurrentScreen;
  83.     private int mNextScreen = INVALID_SCREEN;
  84.  
  85.     private boolean mFirstLayout = true;
  86.  
  87.     private OnScreenSwitchListener mOnScreenSwitchListener;
  88.  
  89.     public RealViewSwitcher(Context context) {
  90.         super(context);
  91.         init();
  92.     }
  93.  
  94.     public RealViewSwitcher(Context context, AttributeSet attrs) {
  95.         super(context, attrs);
  96.         init();
  97.     }
  98.  
  99.     private void init() {
  100.         mScroller = new Scroller(getContext());
  101.  
  102.         final ViewConfiguration configuration = ViewConfiguration.get(getContext());
  103.         mTouchSlop = configuration.getScaledTouchSlop();
  104.         mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
  105.     }
  106.  
  107.     @Override
  108.     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  109.         super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  110.  
  111.         final int width = MeasureSpec.getSize(widthMeasureSpec);
  112.         final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
  113.         if (widthMode != MeasureSpec.EXACTLY) {
  114.             throw new IllegalStateException("ViewSwitcher can only be used in EXACTLY mode.");
  115.         }
  116.  
  117.         final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
  118.         if (heightMode != MeasureSpec.EXACTLY) {
  119.             throw new IllegalStateException("ViewSwitcher can only be used in EXACTLY mode.");
  120.         }
  121.  
  122.         // The children are given the same width and height as the workspace
  123.         final int count = getChildCount();
  124.         for (int i = 0; i < count; i++) {
  125.             getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec);
  126.         }
  127.  
  128.         if (mFirstLayout) {
  129.             scrollTo(mCurrentScreen * width, 0);
  130.             mFirstLayout = false;
  131.         }
  132.     }
  133.  
  134.     @Override
  135.     protected void onLayout(boolean changed, int l, int t, int r, int b) {
  136.         int childLeft = 0;
  137.  
  138.         final int count = getChildCount();
  139.         for (int i = 0; i < count; i++) {
  140.             final View child = getChildAt(i);
  141.             if (child.getVisibility() != View.GONE) {
  142.                 final int childWidth = child.getMeasuredWidth();
  143.                 child.layout(childLeft, 0, childLeft + childWidth, child.getMeasuredHeight());
  144.                 childLeft += childWidth;
  145.             }
  146.         }
  147.     }
  148.  
  149.     @Override
  150.     public boolean onInterceptTouchEvent(MotionEvent ev) {
  151.  
  152.         final int action = ev.getAction();
  153.  
  154.         /*
  155.          * Shortcut the most recurring case: the user is in the dragging state and he is moving his finger. We want to intercept this motion.
  156.          */
  157.         if ((action == MotionEvent.ACTION_MOVE) && (mTouchState != TOUCH_STATE_REST)) {
  158.             if (L)
  159.                 Log.i(TAG, "direct returned from intercept");
  160.             return true;
  161.         }
  162.  
  163.         final float x = ev.getX();
  164.         final float y = ev.getY();
  165.  
  166.         switch (action) {
  167.         case MotionEvent.ACTION_MOVE:
  168.             if (L)
  169.                 Log.i(TAG, "intercept ACTION_MOVE");
  170.  
  171.             /*
  172.              * Locally do absolute value. mLastMotionX is set to the y value of the down event.
  173.              */
  174.             final int xDiff = (int) Math.abs(x - mLastMotionX);
  175.             final int yDiff = (int) Math.abs(y - mLastMotionY);
  176.  
  177.             final int touchSlop = mTouchSlop;
  178.             boolean xMoved = xDiff > touchSlop;
  179.             boolean yMoved = yDiff > touchSlop;
  180.  
  181.             if (xMoved || yMoved) {
  182.                 if (xMoved) {
  183.                     // Scroll if the user moved far enough along the X axis
  184.                     mTouchState = TOUCH_STATE_SCROLLING;
  185.                 }
  186.                 // Either way, cancel any pending longpress
  187.                 if (mAllowLongPress) {
  188.                     mAllowLongPress = false;
  189.                     // Try canceling the long press. It could also have been scheduled
  190.                     // by a distant descendant, so use the mAllowLongPress flag to block
  191.                     // everything
  192.                     final View currentScreen = getChildAt(mCurrentScreen);
  193.                     currentScreen.cancelLongPress();
  194.                 }
  195.             }
  196.             break;
  197.  
  198.         case MotionEvent.ACTION_DOWN:
  199.             if (L)
  200.                 Log.i(TAG, "intercept ACTION_DOWN");
  201.  
  202.             // Remember location of down touch
  203.             mLastMotionX = x;
  204.             mLastMotionY = y;
  205.             mAllowLongPress = true;
  206.  
  207.             /*
  208.              * If being flinged and user touches the screen, initiate drag; otherwise don't. mScroller.isFinished should be false when being flinged.
  209.              */
  210.             mTouchState = mScroller.isFinished() ? TOUCH_STATE_REST : TOUCH_STATE_SCROLLING;
  211.             break;
  212.  
  213.         case MotionEvent.ACTION_UP:
  214.         case MotionEvent.ACTION_CANCEL:
  215.             if (L)
  216.                 Log.i(TAG, "intercept ACTION_UP or ACTION_CANCEL");
  217.             // TODO
  218.             mTouchState = TOUCH_STATE_REST;
  219.             mAllowLongPress = false;
  220.             break;
  221.         }
  222.  
  223.         /*
  224.          * The only time we want to intercept motion events is if we are in the drag mode.
  225.          */
  226.         return mTouchState != TOUCH_STATE_REST;
  227.     }
  228.  
  229.     @Override
  230.     public boolean onTouchEvent(MotionEvent ev) {
  231.         if (mVelocityTracker == null) {
  232.             mVelocityTracker = VelocityTracker.obtain();
  233.         }
  234.         mVelocityTracker.addMovement(ev);
  235.  
  236.         final int action = ev.getAction();
  237.         final float x = ev.getX();
  238.  
  239.         switch (action) {
  240.         case MotionEvent.ACTION_DOWN:
  241.             if (L)
  242.                 Log.i(TAG, "touch ACTION_DOWN");
  243.             /*
  244.              * If being flinged and user touches, stop the fling. isFinished will be false if being flinged.
  245.              */
  246.             if (!mScroller.isFinished()) {
  247.                 mScroller.abortAnimation();
  248.             }
  249.  
  250.             // Remember where the motion event started
  251.             mLastMotionX = x;
  252.             break;
  253.  
  254.         case MotionEvent.ACTION_MOVE:
  255.             if (L)
  256.                 Log.i(TAG, "touch ACTION_MOVE");
  257.  
  258.             if (mTouchState == TOUCH_STATE_SCROLLING) {
  259.                 // Scroll to follow the motion event
  260.                 final int deltaX = (int) (mLastMotionX - x);
  261.                 mLastMotionX = x;
  262.  
  263.                 final int scrollX = getScrollX();
  264.                 if (deltaX < 0) {
  265.                     if (scrollX > 0) {
  266.                         scrollBy(Math.max(-scrollX, deltaX), 0);
  267.                     }
  268.                 } else if (deltaX > 0) {
  269.                     final int availableToScroll = getChildAt(getChildCount() - 1).getRight() - scrollX - getWidth();
  270.                     if (availableToScroll > 0) {
  271.                         scrollBy(Math.min(availableToScroll, deltaX), 0);
  272.                     }
  273.                 }
  274.             }
  275.             break;
  276.  
  277.         case MotionEvent.ACTION_UP:
  278.             if (L)
  279.                 Log.i(TAG, "touch ACTION_UP");
  280.  
  281.             if (mTouchState == TOUCH_STATE_SCROLLING) {
  282.                 final VelocityTracker velocityTracker = mVelocityTracker;
  283.                 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
  284.                 int velocityX = (int) velocityTracker.getXVelocity();
  285.  
  286.                 if (velocityX > SNAP_VELOCITY && mCurrentScreen > 0) {
  287.                     // Fling hard enough to move left
  288.                     snapToScreen(mCurrentScreen - 1);
  289.                 } else if (velocityX < -SNAP_VELOCITY && mCurrentScreen < getChildCount() - 1) {
  290.                     // Fling hard enough to move right
  291.                     snapToScreen(mCurrentScreen + 1);
  292.                 } else {
  293.                     snapToDestination();
  294.                 }
  295.  
  296.                 if (mVelocityTracker != null) {
  297.                     mVelocityTracker.recycle();
  298.                     mVelocityTracker = null;
  299.                 }
  300.             }
  301.  
  302.             mTouchState = TOUCH_STATE_REST;
  303.             break;
  304.  
  305.         case MotionEvent.ACTION_CANCEL:
  306.             if (L)
  307.                 Log.i(TAG, "touch ACTION_CANCEL");
  308.             mTouchState = TOUCH_STATE_REST;
  309.         }
  310.  
  311.         return true;
  312.     }
  313.  
  314.     private void snapToDestination() {
  315.         final int screenWidth = getWidth();
  316.         final int whichScreen = (getScrollX() + (screenWidth / 2)) / screenWidth;
  317.  
  318.         snapToScreen(whichScreen);
  319.     }
  320.  
  321.     private void snapToScreen(int whichScreen) {
  322.         if (!mScroller.isFinished())
  323.             return;
  324.  
  325.         whichScreen = Math.max(0, Math.min(whichScreen, getChildCount() - 1));
  326.  
  327.         mNextScreen = whichScreen;
  328.  
  329.         final int newX = whichScreen * getWidth();
  330.         final int delta = newX - getScrollX();
  331.         mScroller.startScroll(getScrollX(), 0, delta, 0, Math.abs(delta) * 2);
  332.         invalidate();
  333.     }
  334.  
  335.     @Override
  336.     public void computeScroll() {
  337.         if (mScroller.computeScrollOffset()) {
  338.             scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
  339.             postInvalidate();
  340.         } else if (mNextScreen != INVALID_SCREEN) {
  341.             mCurrentScreen = Math.max(0, Math.min(mNextScreen, getChildCount() - 1));
  342.  
  343.             // notify observer about screen change
  344.             if (mOnScreenSwitchListener != null)
  345.                 mOnScreenSwitchListener.onScreenSwitched(mCurrentScreen);
  346.  
  347.             mNextScreen = INVALID_SCREEN;
  348.         }
  349.     }
  350.  
  351.     /**
  352.      * Returns the index of the currently displayed screen.
  353.      *
  354.      * @return The index of the currently displayed screen.
  355.      */
  356.     public int getCurrentScreen() {
  357.         return mCurrentScreen;
  358.     }
  359.  
  360.     /**
  361.      * Sets the current screen.
  362.      *
  363.      * @param currentScreen The new screen.
  364.      */
  365.     public void setCurrentScreen(int currentScreen) {
  366.         mCurrentScreen = Math.max(0, Math.min(currentScreen, getChildCount() - 1));
  367.         scrollTo(mCurrentScreen * getWidth(), 0);
  368.         invalidate();
  369.     }
  370.  
  371.     /**
  372.      * Sets the {@link ViewSwitcher.OnScreenSwitchListener}.
  373.      *
  374.      * @param onScreenSwitchListener The listener for switch events.
  375.      */
  376.     public void setOnScreenSwitchListener(OnScreenSwitchListener onScreenSwitchListener) {
  377.         mOnScreenSwitchListener = onScreenSwitchListener;
  378.     }
  379.  
  380. }
Advertisement
Add Comment
Please, Sign In to add comment