Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(115)

Unified Diff: chrome/android/java/src/org/chromium/chrome/browser/widget/BottomSheet.java

Issue 2625923002: Introduce the bottom sheet class for Chrome Home (Closed)
Patch Set: rebase Created 3 years, 11 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
Index: chrome/android/java/src/org/chromium/chrome/browser/widget/BottomSheet.java
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/BottomSheet.java b/chrome/android/java/src/org/chromium/chrome/browser/widget/BottomSheet.java
new file mode 100644
index 0000000000000000000000000000000000000000..83dbfd4c07a7a341742f61cddb230a028b3c5bcc
--- /dev/null
+++ b/chrome/android/java/src/org/chromium/chrome/browser/widget/BottomSheet.java
@@ -0,0 +1,400 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package org.chromium.chrome.browser.widget;
+
+import android.animation.Animator;
+import android.animation.AnimatorListenerAdapter;
+import android.animation.ObjectAnimator;
+import android.content.Context;
+import android.graphics.Region;
+import android.util.AttributeSet;
+import android.view.GestureDetector;
+import android.view.MotionEvent;
+import android.view.VelocityTracker;
+import android.view.View;
+import android.view.animation.DecelerateInterpolator;
+import android.view.animation.Interpolator;
+import android.widget.LinearLayout;
+
+import org.chromium.chrome.browser.util.MathUtils;
+
+/**
+ * This class defines the behavior of a bottom sheet that has multiple states and a persistently
Ian Wen 2017/01/17 18:39:48 Nit: I would say this class defines the bottom she
mdjones 2017/01/17 21:29:45 Done.
+ * showing toolbar. Namely, the states are:
+ * - PEEK: Only the toolbar is visible at the bottom of the screen.
+ * - HALF: The sheet is expanded to consume around half of the screen.
+ * - FULL: The sheet is expanded to its full height.
+ *
+ * All the computation in this file is based off of the bottom of the screen instead of the top
+ * for simplicity. This means that the bottom of the screen is 0 on the Y axis.
+ */
+public class BottomSheet extends LinearLayout {
+ /** The different states that the bottom sheet can have. */
+ public static final int STATE_PEEK = 0;
+ public static final int STATE_HALF = 1;
+ public static final int STATE_FULL = 2;
+
+ /** The base duration of the settling animation of the sheet. */
+ private static final long BASE_ANIMATION_DURATION_MS = 218;
+
+ /**
+ * The fraction of the way to the next state the sheet must be swiped to animate there when
+ * released. A smaller value here means a smaller swipe is needed to move the sheet around.
+ */
+ private static final float THRESHOLD_TO_NEXT_STATE = 0.5f;
+
+ /** The minimum y/x ratio that a scroll must have to be considered vertical. */
+ private static final float MIN_VERTICAL_SCROLL_SLOPE = 2.0f;
+
+ /**
+ * Information about the different scroll states of the sheet. Order is important for these,
+ * they go from smallest to largest.
+ */
+ private final int[] mStates = new int[] {STATE_PEEK, STATE_HALF, STATE_FULL};
+ private final float[] mStateRatios = new float[] {0.0f, 0.55f, 0.95f};
+
+ /** The interpolator that the height animator uses. */
+ private final Interpolator mInterpolator = new DecelerateInterpolator(1.0f);
+
+ /** For detecting scroll and fling events on the bottom sheet. */
+ private GestureDetector mGestureDetector;
+
+ /** Whether or not the user is scrolling the bottom sheet. */
+ private boolean mIsScrolling;
+
+ /** Track the velocity of the user's scrolls to determine up or down direction. */
+ private VelocityTracker mVelocityTracker;
+
+ /** The animator used to move the sheet to a fixed state when released by the user. */
+ private ObjectAnimator mSettleAnimator;
+
+ /** The height of the toolbar. */
+ private float mToolbarHeight;
+
+ /** The height of the view that contains the bottom sheet. */
+ private float mContainerHeight;
+
+ /** The current sheet state. If the sheet is moving, this will be the target state. */
+ private int mCurrentState;
+
+ /**
+ * This class is responsible for detecting swipe and scroll events on the bottom sheet or
+ * ignoring them when appropriate.
+ */
+ private class BottomSheetSwipeDetector extends GestureDetector.SimpleOnGestureListener {
+ @Override
+ public boolean onDown(MotionEvent e) {
+ return true;
+ }
+
+ @Override
+ public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
+ float distanceY) {
+ // Only start scrolling if the scroll is up or down. If the user is already scrolling,
+ // continue moving the sheet.
+ float slope = Math.abs(distanceX) > 0f ? Math.abs(distanceY) / Math.abs(distanceX) : 0f;
+ if (!mIsScrolling && slope < MIN_VERTICAL_SCROLL_SLOPE) {
+ mVelocityTracker.clear();
+ return false;
+ }
+
+ // Cancel the settling animation if it is running so it doesn't conflict with where the
gone 2017/01/19 18:00:41 double space before with
mdjones 2017/01/19 21:49:08 Done.
+ // user wants to move the sheet.
+ cancelAnimation();
+
+ mVelocityTracker.addMovement(e2);
+
+ float currentShownRatio = getSheetOffsetFromBottom() / mContainerHeight;
Ian Wen 2017/01/17 18:39:48 This code will crash if container has height of 0,
mdjones 2017/01/17 21:29:45 Changed to handle the 0 case. I think the code sho
+
+ // If the sheet is in the max position, don't move if the scroll is upward.
+ if (currentShownRatio >= mStateRatios[mStateRatios.length - 1]
+ && distanceY > 0) {
+ mIsScrolling = false;
+ return false;
+ }
+
+ // Similarly, if the sheet is in the min position, don't move if the scroll is downward.
+ if (currentShownRatio <= mStateRatios[0] && distanceY < 0) {
+ mIsScrolling = false;
+ return false;
+ }
+
+ float newOffset = getSheetOffsetFromBottom() + distanceY;
+ setSheetOffsetFromBottom(MathUtils.clamp(newOffset, getMinOffset(), getMaxOffset()));
+
+ mIsScrolling = true;
+ return true;
+ }
+
+ @Override
+ public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
+ float velocityY) {
+ cancelAnimation();
+
+ // Figure out the projected state of the sheet and animate there. Note that a swipe up
+ // will have a negative velocity, swipe down will have a positive velocity. Negate this
+ // values so that the logic is more intuitive.
+ int targetState = getTargetSheetState(
+ getSheetOffsetFromBottom() + getFlingDistance(-velocityY), -velocityY);
+ setSheetState(targetState, true);
+ mIsScrolling = false;
+
+ return true;
+ }
+ }
+
+ /**
+ * Constructor for inflation from XML.
+ * @param context An Android context.
+ * @param atts The XML attributes.
+ */
+ public BottomSheet(Context context, AttributeSet atts) {
+ super(context, atts);
+
+ mVelocityTracker = VelocityTracker.obtain();
+
+ mGestureDetector = new GestureDetector(context, new BottomSheetSwipeDetector());
+ mGestureDetector.setIsLongpressEnabled(false);
+ }
+
+ @Override
+ public boolean onInterceptTouchEvent(MotionEvent e) {
+ // The incoming motion event may have been adjusted by the view sending it down. Create a
+ // motion event with the raw (x, y) coordinates of the original so the gesture detector
+ // functions properly.
+ mGestureDetector.onTouchEvent(getRawMotionEvent(e));
+ return mIsScrolling;
+ }
+
+ @Override
+ public boolean onTouchEvent(MotionEvent e) {
+ // The down event is interpreted above in onInterceptTouchEvent, it does not need to be
+ // interpreted a second time.
+ if (e.getActionMasked() != MotionEvent.ACTION_DOWN) {
+ mGestureDetector.onTouchEvent(getRawMotionEvent(e));
+ }
+
+ // If the user is scrolling and the event is a cancel or up action, update scroll state
+ // and return.
+ if (e.getActionMasked() == MotionEvent.ACTION_UP
+ || e.getActionMasked() == MotionEvent.ACTION_CANCEL) {
+ mIsScrolling = false;
+
+ mVelocityTracker.computeCurrentVelocity(1000);
+
+ // If an animation was not created to settle the sheet at some state, do it now.
+ if (mSettleAnimator == null) {
+ // Negate velocity so a positive number indicates a swipe up.
+ float currentVelocity = -mVelocityTracker.getYVelocity();
+ int targetState = getTargetSheetState(getSheetOffsetFromBottom(), currentVelocity);
+
+ setSheetState(targetState, true);
+ }
+ }
+
+ return true;
+ }
+
+ @Override
+ public boolean gatherTransparentRegion(Region region) {
+ // TODO(mdjones): Figure out what this should actually be set to since the view animates
+ // without necessarily calling this method again.
+ region.setEmpty();
Ian Wen 2017/01/17 18:39:48 Q: what will happen if you don't have this line?
mdjones 2017/01/17 21:29:46 The sheet will be visually clipped to the height o
+ return true;
+ }
+
+ /**
+ * Add layout change listeners to the views that the bottom sheet depends on. Namely the
+ * heights of the root view and control container are important as they are used in many of the
+ * calculations in this class.
+ * @param root The container of the bottom sheet.
+ * @param controlContainer The container for the toolbar.
+ */
+ public void init(View root, View controlContainer) {
+ mToolbarHeight = controlContainer.getHeight();
+ mCurrentState = STATE_PEEK;
+
+ // Listen to height changes on the root.
+ root.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
+ public void onLayoutChange(View v, int left, int top, int right, int bottom,
+ int oldLeft, int oldTop, int oldRight, int oldBottom) {
+ mContainerHeight = bottom - top;
+ updateSheetPeekHeight(mToolbarHeight, mContainerHeight);
+ setSheetState(mCurrentState, false);
+ }
+ });
+
+ // Listen to height changes on the toolbar.
+ controlContainer.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
+ public void onLayoutChange(View v, int left, int top, int right, int bottom,
+ int oldLeft, int oldTop, int oldRight, int oldBottom) {
+ mToolbarHeight = bottom - top;
+ updateSheetPeekHeight(mToolbarHeight, mContainerHeight);
+ setSheetState(mCurrentState, false);
+ }
+ });
+ }
+
+ /**
+ * Get the unadjusted version of a MotionEvent.
+ * @param e The original event.
+ * @return The unadjusted version of the event.
+ */
+ private MotionEvent getRawMotionEvent(MotionEvent e) {
Ian Wen 2017/01/17 18:39:48 This method creates a new object. I would rename i
mdjones 2017/01/17 21:29:46 Done.
+ MotionEvent rawEvent = MotionEvent.obtain(e);
+ rawEvent.setLocation(e.getRawX(), e.getRawY());
+ return rawEvent;
+ }
+
+ /**
+ * Update the bottom sheet's peeking height.
Ian Wen 2017/01/17 18:39:48 s/Update/Updates. Same with all java docs for this
mdjones 2017/01/17 21:29:45 Done.
+ * @param toolbarHeight The height of the toolbar control container.
+ * @param containerHeight The height of the bottom sheet's container.
+ */
+ private void updateSheetPeekHeight(float toolbarHeight, float containerHeight) {
+ if (containerHeight <= 0) return;
+
+ mStateRatios[0] = toolbarHeight / containerHeight;
+ }
+
+ /**
+ * Cancel and null the height animation if it exists.
+ */
+ private void cancelAnimation() {
+ if (mSettleAnimator == null) return;
+ mSettleAnimator.cancel();
+ mSettleAnimator = null;
+ }
+
+ /**
+ * Create the sheet's animation to a target state.
+ * @param targetState The target state.
+ */
+ private void createSettleAnimation(int targetState) {
+ mCurrentState = targetState;
+ mSettleAnimator = ObjectAnimator.ofFloat(
+ this, View.TRANSLATION_Y, mContainerHeight - getSheetHeightForState(targetState));
+ mSettleAnimator.setDuration(BASE_ANIMATION_DURATION_MS);
+ mSettleAnimator.setInterpolator(mInterpolator);
+
+ // When the animation is canceled or ends, reset the handle to null.
+ mSettleAnimator.addListener(new AnimatorListenerAdapter() {
+ @Override
+ public void onAnimationEnd(Animator animator) {
+ mSettleAnimator = null;
+ }
+ });
+
+ mSettleAnimator.start();
+ }
+
+ /**
+ * Get the distance of a fling based on the velocity and the base animation time. This formula
+ * assumes the deceleration curve is quadratic (t^2), hence the displacement formula should be:
+ * displacement = initialVelocity * duration / 2.
+ * @param velocity The velocity of the fling.
+ * @return The distance the fling would cover.
+ */
+ private float getFlingDistance(float velocity) {
+ // This includes conversion from seconds to ms.
+ return velocity * BASE_ANIMATION_DURATION_MS / 2000f;
+ }
+
+ /**
+ * Get the maximum offset of the bottom sheet.
+ * @return The max offset.
+ */
+ private float getMaxOffset() {
+ return mStateRatios[mStateRatios.length - 1] * mContainerHeight;
+ }
+
+ /**
+ * Get the minimum offset of the bottom sheet.
+ * @return The min offset.
+ */
+ private float getMinOffset() {
+ return mStateRatios[0] * mContainerHeight;
+ }
+
+ /**
+ * Get the sheet's offset from the bottom of the screen.
+ * @return The sheet's distance from the bottom of the screen.
+ */
+ private float getSheetOffsetFromBottom() {
+ return mContainerHeight - getTranslationY();
+ }
+
+ /**
+ * Set the sheet's offset relative to the bottom of the screen.
+ * @param offset The offset that the sheet should be.
+ */
+ private void setSheetOffsetFromBottom(float offset) {
+ setTranslationY(mContainerHeight - offset);
+ }
+
+ /**
+ * Move the sheet to the provided state.
+ * @param state The state to move the panel to.
+ * @param animate If true, the sheet will animate to the provided state, otherwise it will
+ * move there instantly.
+ */
+ private void setSheetState(int state, boolean animate) {
+ mCurrentState = state;
+
+ if (animate) {
+ createSettleAnimation(state);
+ } else {
+ setSheetOffsetFromBottom(getSheetHeightForState(state));
+ }
+ }
+
+ /**
+ * Get the height of the bottom sheet based on a provided state.
+ * @param state The state to get the height from.
+ * @return The height of the sheet at the provided state.
+ */
+ private float getSheetHeightForState(int state) {
+ return mStateRatios[state] * mContainerHeight;
+ }
+
+ /**
+ * Get the target state of the sheet based on the sheet's height and velocity.
+ * @param sheetHeight The current height of the sheet.
+ * @param yVelocity The current Y velocity of the sheet. This is only used for determining the
+ * scroll or fling direction. If this value is positive, the movement is from
+ * bottom to top.
+ * @return The target state of the bottom sheet.
+ */
+ private int getTargetSheetState(float sheetHeight, float yVelocity) {
+ if (sheetHeight <= getMinOffset()) return STATE_PEEK;
+ if (sheetHeight >= getMaxOffset()) return STATE_FULL;
+
+ // First, find the two states that the sheet height is between.
+ int nextState = mStates[0];
+ int prevState = nextState;
+ for (int i = 0; i < mStates.length; i++) {
+ prevState = nextState;
+ nextState = mStates[i];
+ // The values in PanelState are ascending, they should be kept that way in order for
+ // this to work.
+ if (sheetHeight >= getSheetHeightForState(prevState)
+ && sheetHeight < getSheetHeightForState(nextState)) {
+ break;
+ }
+ }
+
+ // If the desired height is close enough to a certain state, depending on the direction of
+ // the velocity, move to that state.
+ float lowerBound = getSheetHeightForState(prevState);
+ float distance = getSheetHeightForState(nextState) - lowerBound;
+ float thresholdToNextState =
+ yVelocity < 0.0f ? THRESHOLD_TO_NEXT_STATE : 1.0f - THRESHOLD_TO_NEXT_STATE;
+ if ((sheetHeight - lowerBound) / distance > thresholdToNextState) {
+ return nextState;
+ } else {
+ return prevState;
+ }
+ }
+}

Powered by Google App Engine
This is Rietveld 408576698