Java Code Examples for androidx.core.math.MathUtils

The following examples show how to use androidx.core.math.MathUtils. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: DateTimePicker   Source File: TextInputTimePickerView.java    License: Apache License 2.0 6 votes vote down vote up
private boolean parseAndSetHourInternal(String input) {
    try {
        final int hour = Integer.parseInt(input);
        if (!isValidLocalizedHour(hour)) {
            final int minHour = mHourFormatStartsAtZero ? 0 : 1;
            final int maxHour = mIs24Hour ? 23 : 11 + minHour;
            mListener.onValueChanged(HOURS, getHourOfDayFromLocalizedHour(
                    MathUtils.clamp(hour, minHour, maxHour)));
            return false;
        }
        mListener.onValueChanged(HOURS, getHourOfDayFromLocalizedHour(hour));
        return true;
    } catch (NumberFormatException e) {
        // Do nothing since we cannot parse the input.
        return false;
    }
}
 
Example 2
int setHeaderTopBottomOffset(
    CoordinatorLayout parent, V header, int newOffset, int minOffset, int maxOffset) {
  final int curOffset = getTopAndBottomOffset();
  int consumed = 0;

  if (minOffset != 0 && curOffset >= minOffset && curOffset <= maxOffset) {
    // If we have some scrolling range, and we're currently within the min and max
    // offsets, calculate a new offset
    newOffset = MathUtils.clamp(newOffset, minOffset, maxOffset);

    if (curOffset != newOffset) {
      setTopAndBottomOffset(newOffset);
      // Update how much dy we have consumed
      consumed = curOffset - newOffset;
    }
  }

  return consumed;
}
 
Example 3
@Override
public void onOffsetChanged(AppBarLayout layout, int verticalOffset) {
    currentOffset = verticalOffset;

    final int insetTop = lastInsets != null ? lastInsets.getSystemWindowInsetTop() : 0;

    for (int i = 0, z = getChildCount(); i < z; i++) {
        final View child = getChildAt(i);
        final LayoutParams lp = (LayoutParams) child.getLayoutParams();
        final ViewOffsetHelper offsetHelper = getViewOffsetHelper(child);

        switch (lp.collapseMode) {
            case LayoutParams.COLLAPSE_MODE_PIN:
                offsetHelper.setTopAndBottomOffset(
                    MathUtils.clamp(-verticalOffset, 0, getMaxOffsetForPinChild(child)));
                break;
            case LayoutParams.COLLAPSE_MODE_PARALLAX:
                offsetHelper.setTopAndBottomOffset(Math.round(-verticalOffset * lp.parallaxMult));
                break;
            default:
                break;
        }
    }

    // Show or hide the scrims if needed
    updateScrimVisibility();

    if (statusBarScrim != null && insetTop > 0) {
        ViewCompat.postInvalidateOnAnimation(SubtitleCollapsingToolbarLayout.this);
    }

    // Update the collapsing text's fraction
    final int expandRange = getHeight()
        - ViewCompat.getMinimumHeight(SubtitleCollapsingToolbarLayout.this)
        - insetTop;
    collapsingTextHelper.setExpansionFraction(Math.abs(verticalOffset) / (float) expandRange);
}
 
Example 4
/**
 * Set the value indicating the current scroll value. This decides how much of the background will
 * be displayed, as well as the title metrics/positioning.
 *
 * <p>A value of {@code 0.0} indicates that the layout is fully expanded. A value of {@code 1.0}
 * indicates that the layout is fully collapsed.
 */
public void setExpansionFraction(float fraction) {
    fraction = MathUtils.clamp(fraction, 0f, 1f);

    if (fraction != expandedFraction) {
        expandedFraction = fraction;
        calculateCurrentOffsets();
    }
}
 
Example 5
Source Project: DateTimePicker   Source File: TextInputTimePickerView.java    License: Apache License 2.0 5 votes vote down vote up
private boolean parseAndSetMinuteInternal(String input) {
    try {
        final int minutes = Integer.parseInt(input);
        if (minutes < 0 || minutes > 59) {
            mListener.onValueChanged(MINUTES, MathUtils.clamp(minutes, 0, 59));
            return false;
        }
        mListener.onValueChanged(MINUTES, minutes);
        return true;
    } catch (NumberFormatException e) {
        // Do nothing since we cannot parse the input.
        return false;
    }
}
 
Example 6
Source Project: DateTimePicker   Source File: RadialTimePickerView.java    License: Apache License 2.0 5 votes vote down vote up
private void adjustPicker(int step) {
    final int stepSize;
    final int initialStep;
    final int maxValue;
    final int minValue;
    if (mShowHours) {
        stepSize = 1;

        final int currentHour24 = getCurrentHour();
        if (mIs24HourMode) {
            initialStep = currentHour24;
            minValue = 0;
            maxValue = 23;
        } else {
            initialStep = hour24To12(currentHour24);
            minValue = 1;
            maxValue = 12;
        }
    } else {
        stepSize = 5;
        initialStep = getCurrentMinute() / stepSize;
        minValue = 0;
        maxValue = 55;
    }

    final int nextValue = (initialStep + step) * stepSize;
    final int clampedValue = MathUtils.clamp(nextValue, minValue, maxValue);//MathUtils.constrain(nextValue, minValue, maxValue);
    if (mShowHours) {
        setCurrentHour(clampedValue);
    } else {
        setCurrentMinute(clampedValue);
    }
}
 
Example 7
Source Project: material-components-android   Source File: TocFragment.java    License: Apache License 2.0 5 votes vote down vote up
private int calculateGridSpanCount() {
  DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
  int displayWidth = displayMetrics.widthPixels;
  int itemSize = getResources().getDimensionPixelSize(R.dimen.cat_toc_item_size);
  int gridSpanCount = displayWidth / itemSize;
  return MathUtils.clamp(gridSpanCount, GRID_SPAN_COUNT_MIN, GRID_SPAN_COUNT_MAX);
}
 
Example 8
Source Project: material-components-android   Source File: AppBarLayout.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  super.onMeasure(widthMeasureSpec, heightMeasureSpec);

  // If we're set to handle system windows but our first child is not, we need to add some
  // height to ourselves to pad the first child down below the status bar
  final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
  if (heightMode != MeasureSpec.EXACTLY
      && ViewCompat.getFitsSystemWindows(this)
      && shouldOffsetFirstChild()) {
    int newHeight = getMeasuredHeight();
    switch (heightMode) {
      case MeasureSpec.AT_MOST:
        // For AT_MOST, we need to clamp our desired height with the max height
        newHeight =
            MathUtils.clamp(
                getMeasuredHeight() + getTopInset(), 0, MeasureSpec.getSize(heightMeasureSpec));
        break;
      case MeasureSpec.UNSPECIFIED:
        // For UNSPECIFIED we can use any height so just add the top inset
        newHeight += getTopInset();
        break;
      default: // fall out
    }
    setMeasuredDimension(getMeasuredWidth(), newHeight);
  }

  invalidateScrollRanges();
}
 
Example 9
@Override
public void onOffsetChanged(AppBarLayout layout, int verticalOffset) {
  currentOffset = verticalOffset;

  final int insetTop = lastInsets != null ? lastInsets.getSystemWindowInsetTop() : 0;

  for (int i = 0, z = getChildCount(); i < z; i++) {
    final View child = getChildAt(i);
    final LayoutParams lp = (LayoutParams) child.getLayoutParams();
    final ViewOffsetHelper offsetHelper = getViewOffsetHelper(child);

    switch (lp.collapseMode) {
      case LayoutParams.COLLAPSE_MODE_PIN:
        offsetHelper.setTopAndBottomOffset(
            MathUtils.clamp(-verticalOffset, 0, getMaxOffsetForPinChild(child)));
        break;
      case LayoutParams.COLLAPSE_MODE_PARALLAX:
        offsetHelper.setTopAndBottomOffset(Math.round(-verticalOffset * lp.parallaxMult));
        break;
      default:
        break;
    }
  }

  // Show or hide the scrims if needed
  updateScrimVisibility();

  if (statusBarScrim != null && insetTop > 0) {
    ViewCompat.postInvalidateOnAnimation(CollapsingToolbarLayout.this);
  }

  // Update the collapsing text's fraction
  final int expandRange =
      getHeight() - ViewCompat.getMinimumHeight(CollapsingToolbarLayout.this) - insetTop;
  collapsingTextHelper.setExpansionFraction(Math.abs(verticalOffset) / (float) expandRange);
}
 
Example 10
/**
 * Set the value indicating the current scroll value. This decides how much of the background will
 * be displayed, as well as the title metrics/positioning.
 *
 * <p>A value of {@code 0.0} indicates that the layout is fully expanded. A value of {@code 1.0}
 * indicates that the layout is fully collapsed.
 */
public void setExpansionFraction(float fraction) {
  fraction = MathUtils.clamp(fraction, 0f, 1f);

  if (fraction != expandedFraction) {
    expandedFraction = fraction;
    calculateCurrentOffsets();
  }
}
 
Example 11
Source Project: RecyclerViewExtensions   Source File: DragDropHelper.java    License: MIT License 5 votes vote down vote up
/**
 * Offsets the dragged view based on the touch position, clamping its location to the parent.
 */
private void handleTranslation(@NonNull RecyclerView.ViewHolder viewHolder, int startLeft, int startTop) {
    int width = viewHolder.itemView.getWidth();
    int height = viewHolder.itemView.getHeight();
    int maxLeft = mRecyclerView.getWidth() - width;
    int maxTop = mRecyclerView.getHeight() - height;

    int left = MathUtils.clamp(startLeft + (mTouchCurrentX - mTouchStartX), 0, maxLeft);
    int top = MathUtils.clamp(startTop + (mTouchCurrentY - mTouchStartY), 0, maxTop);

    setTranslation(viewHolder, left - viewHolder.itemView.getLeft(), top - viewHolder.itemView.getTop());
}
 
Example 12
Source Project: AndroidFastScroll   Source File: FastScroller.java    License: Apache License 2.0 4 votes vote down vote up
private void onPreDraw() {

        updateScrollbarState();
        mTrackView.setVisibility(mScrollbarEnabled ? View.VISIBLE : View.INVISIBLE);
        mThumbView.setVisibility(mScrollbarEnabled ? View.VISIBLE : View.INVISIBLE);
        if (!mScrollbarEnabled) {
            mPopupView.setVisibility(View.INVISIBLE);
            return;
        }

        int layoutDirection = mView.getLayoutDirection();
        mTrackView.setLayoutDirection(layoutDirection);
        mThumbView.setLayoutDirection(layoutDirection);
        mPopupView.setLayoutDirection(layoutDirection);

        boolean isLayoutRtl = layoutDirection == View.LAYOUT_DIRECTION_RTL;
        int viewWidth = mView.getWidth();
        int viewHeight = mView.getHeight();

        Rect padding = getPadding();
        int trackLeft = isLayoutRtl ? padding.left : viewWidth - padding.right - mTrackWidth;
        layoutView(mTrackView, trackLeft, padding.top, trackLeft + mTrackWidth,
                viewHeight - padding.bottom);
        int thumbLeft = isLayoutRtl ? padding.left : viewWidth - padding.right - mThumbWidth;
        int thumbTop = padding.top + mThumbOffset;
        layoutView(mThumbView, thumbLeft, thumbTop, thumbLeft + mThumbWidth,
                thumbTop + mThumbHeight);

        String popupText = mViewHelper.getPopupText();
        boolean hasPopup = !TextUtils.isEmpty(popupText);
        mPopupView.setVisibility(hasPopup ? View.VISIBLE : View.INVISIBLE);
        if (hasPopup) {
            FrameLayout.LayoutParams popupLayoutParams = (FrameLayout.LayoutParams)
                    mPopupView.getLayoutParams();
            if (!Objects.equals(mPopupView.getText(), popupText)) {
                mPopupView.setText(popupText);
                int widthMeasureSpec = ViewGroup.getChildMeasureSpec(
                        View.MeasureSpec.makeMeasureSpec(viewWidth, View.MeasureSpec.EXACTLY),
                        padding.left + padding.right + mThumbWidth + popupLayoutParams.leftMargin
                                + popupLayoutParams.rightMargin, popupLayoutParams.width);
                int heightMeasureSpec = ViewGroup.getChildMeasureSpec(
                        View.MeasureSpec.makeMeasureSpec(viewHeight, View.MeasureSpec.EXACTLY),
                        padding.top + padding.bottom + popupLayoutParams.topMargin
                                + popupLayoutParams.bottomMargin, popupLayoutParams.height);
                mPopupView.measure(widthMeasureSpec, heightMeasureSpec);
            }
            int popupWidth = mPopupView.getMeasuredWidth();
            int popupHeight = mPopupView.getMeasuredHeight();
            int popupLeft = isLayoutRtl ? padding.left + mThumbWidth + popupLayoutParams.leftMargin
                    : viewWidth - padding.right - mThumbWidth - popupLayoutParams.rightMargin
                    - popupWidth;
            int popupAnchorY;
            switch (popupLayoutParams.gravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
                case Gravity.LEFT:
                default:
                    popupAnchorY = 0;
                    break;
                case Gravity.CENTER_HORIZONTAL:
                    popupAnchorY = popupHeight / 2;
                    break;
                case Gravity.RIGHT:
                    popupAnchorY = popupHeight;
                    break;
            }
            int thumbAnchorY;
            switch (popupLayoutParams.gravity & Gravity.VERTICAL_GRAVITY_MASK) {
                case Gravity.TOP:
                default:
                    thumbAnchorY = mThumbView.getPaddingTop();
                    break;
                case Gravity.CENTER_VERTICAL: {
                    int thumbPaddingTop = mThumbView.getPaddingTop();
                    thumbAnchorY = thumbPaddingTop + (mThumbHeight - thumbPaddingTop
                            - mThumbView.getPaddingBottom()) / 2;
                    break;
                }
                case Gravity.BOTTOM:
                    thumbAnchorY = mThumbHeight - mThumbView.getPaddingBottom();
                    break;
            }
            int popupTop = MathUtils.clamp(thumbTop + thumbAnchorY - popupAnchorY,
                    padding.top + popupLayoutParams.topMargin,
                    viewHeight - padding.bottom - popupLayoutParams.bottomMargin - popupHeight);
            layoutView(mPopupView, popupLeft, popupTop, popupLeft + popupWidth,
                    popupTop + popupHeight);
        }
    }
 
Example 13
Source Project: AndroidFastScroll   Source File: FastScroller.java    License: Apache License 2.0 4 votes vote down vote up
private void scrollToThumbOffset(int thumbOffset) {
    int thumbOffsetRange = getThumbOffsetRange();
    thumbOffset = MathUtils.clamp(thumbOffset, 0, thumbOffsetRange);
    int scrollOffset = (int) ((long) getScrollOffsetRange() * thumbOffset / thumbOffsetRange);
    mViewHelper.scrollTo(scrollOffset);
}
 
Example 14
@Override
public int clampViewPositionVertical(@NonNull View child, int top, int dy) {
  return MathUtils.clamp(
      top, getExpandedOffset(), hideable ? parentHeight : collapsedOffset);
}
 
Example 15
final int getOverlapPixelsForOffset(final View header) {
  return overlayTop == 0
      ? 0
      : MathUtils.clamp((int) (getOverlapRatioForOffset(header) * overlayTop), 0, overlayTop);
}
 
Example 16
Source Project: material-components-android   Source File: AppBarLayout.java    License: Apache License 2.0 4 votes vote down vote up
private void snapToChildIfNeeded(CoordinatorLayout coordinatorLayout, @NonNull T abl) {
  final int offset = getTopBottomOffsetForScrollingSibling();
  final int offsetChildIndex = getChildIndexOnOffset(abl, offset);
  if (offsetChildIndex >= 0) {
    final View offsetChild = abl.getChildAt(offsetChildIndex);
    final LayoutParams lp = (LayoutParams) offsetChild.getLayoutParams();
    final int flags = lp.getScrollFlags();

    if ((flags & LayoutParams.FLAG_SNAP) == LayoutParams.FLAG_SNAP) {
      // We're set the snap, so animate the offset to the nearest edge
      int snapTop = -offsetChild.getTop();
      int snapBottom = -offsetChild.getBottom();

      if (offsetChildIndex == abl.getChildCount() - 1) {
        // If this is the last child, we need to take the top inset into account
        snapBottom += abl.getTopInset();
      }

      if (checkFlag(flags, LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED)) {
        // If the view is set only exit until it is collapsed, we'll abide by that
        snapBottom += ViewCompat.getMinimumHeight(offsetChild);
      } else if (checkFlag(
          flags, LayoutParams.FLAG_QUICK_RETURN | LayoutParams.SCROLL_FLAG_ENTER_ALWAYS)) {
        // If it's set to always enter collapsed, it actually has two states. We
        // select the state and then snap within the state
        final int seam = snapBottom + ViewCompat.getMinimumHeight(offsetChild);
        if (offset < seam) {
          snapTop = seam;
        } else {
          snapBottom = seam;
        }
      }

      if (checkFlag(flags, LayoutParams.SCROLL_FLAG_SNAP_MARGINS)) {
        // Update snap destinations to include margins
        snapTop += lp.topMargin;
        snapBottom -= lp.bottomMargin;
      }

      final int newOffset = offset < (snapBottom + snapTop) / 2 ? snapBottom : snapTop;
      animateOffsetTo(
          coordinatorLayout, abl, MathUtils.clamp(newOffset, -abl.getTotalScrollRange(), 0), 0);
    }
  }
}
 
Example 17
Source Project: material-components-android   Source File: AppBarLayout.java    License: Apache License 2.0 4 votes vote down vote up
@Override
int setHeaderTopBottomOffset(
    @NonNull CoordinatorLayout coordinatorLayout,
    @NonNull T appBarLayout,
    int newOffset,
    int minOffset,
    int maxOffset) {
  final int curOffset = getTopBottomOffsetForScrollingSibling();
  int consumed = 0;

  if (minOffset != 0 && curOffset >= minOffset && curOffset <= maxOffset) {
    // If we have some scrolling range, and we're currently within the min and max
    // offsets, calculate a new offset
    newOffset = MathUtils.clamp(newOffset, minOffset, maxOffset);
    if (curOffset != newOffset) {
      final int interpolatedOffset =
          appBarLayout.hasChildWithInterpolator()
              ? interpolateOffset(appBarLayout, newOffset)
              : newOffset;

      final boolean offsetChanged = setTopAndBottomOffset(interpolatedOffset);

      // Update how much dy we have consumed
      consumed = curOffset - newOffset;
      // Update the stored sibling offset
      offsetDelta = newOffset - interpolatedOffset;

      if (!offsetChanged && appBarLayout.hasChildWithInterpolator()) {
        // If the offset hasn't changed and we're using an interpolated scroll
        // then we need to keep any dependent views updated. CoL will do this for
        // us when we move, but we need to do it manually when we don't (as an
        // interpolated scroll may finish early).
        coordinatorLayout.dispatchDependentViewsChanged(appBarLayout);
      }

      // Dispatch the updates to any listeners
      appBarLayout.onOffsetChanged(getTopAndBottomOffset());

      // Update the AppBarLayout's drawable state (for any elevation changes)
      updateAppBarLayoutDrawableState(
          coordinatorLayout,
          appBarLayout,
          newOffset,
          newOffset < curOffset ? -1 : 1,
          false /* forceJump */);
    }
  } else {
    // Reset the offset delta
    offsetDelta = 0;
  }

  updateAccessibilityActions(coordinatorLayout, appBarLayout);
  return consumed;
}
 
Example 18
@Override
public int clampViewPositionVertical(@NonNull View child, int top, int dy) {
    return MathUtils.clamp(
            top, getExpandedOffset(), hideable ? parentHeight : collapsedOffset);
}
 
Example 19
Source Project: ARVI   Source File: VolumeInfo.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Sets the Audio Volume.
 *
 * @param audioVolume the audio volume ratio (a value between 0.0 and 1.0)
 * @return the same instance of the {@link VolumeInfo} for chaining purposes.
 */
@NonNull
public final VolumeInfo setVolume(@FloatRange(from = 0.0, to = 1.0) float audioVolume) {
    this.audioVolume = MathUtils.clamp(audioVolume, 0f, 1f);
    return this;
}
 
Example 20
Source Project: DateTimePicker   Source File: TimePicker.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Sets the currently selected hour using 24-hour time.
 *
 * @param hour the hour to set, in the range (0-23)
 * @see #getHour()
 */
public void setHour(@IntRange(from = 0, to = 23) int hour) {
    mDelegate.setHour(MathUtils.clamp(hour, 0, 23));
}
 
Example 21
Source Project: DateTimePicker   Source File: TimePicker.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Sets the currently selected minute.
 *
 * @param minute the minute to set, in the range (0-59)
 * @see #getMinute()
 */
public void setMinute(@IntRange(from = 0, to = 59) int minute) {
    mDelegate.setMinute(MathUtils.clamp(minute, 0, 59));
}