androidx.core.view.ViewCompat Java Examples

The following examples show how to use androidx.core.view.ViewCompat. 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 File: PendingItemAnimator.java    From FlexibleAdapter with Apache License 2.0 6 votes vote down vote up
/**
 * Do whatever you need to do before animation.
 **/
protected boolean prepHolderForAnimateMove(final H holder, int fromX, int fromY, int toX, int toY) {
    final View view = holder.itemView;
    int deltaX = toX - fromX;
    int deltaY = toY - fromY;
    if (deltaX == 0 && deltaY == 0) {
        dispatchMoveFinished(holder);
        return false;
    }
    if (deltaX != 0) {
        ViewCompat.setTranslationX(view, -deltaX);
    }
    if (deltaY != 0) {
        ViewCompat.setTranslationY(view, -deltaY);
    }
    return true;
}
 
Example #2
Source File: DuoDrawerLayout.java    From duo-navigation-drawer with Apache License 2.0 6 votes vote down vote up
/**
 * Open the drawer animated.
 */
public void openDrawer() {
    int drawerWidth = (int) (getWidth() * mMarginFactor);
    if (drawerWidth == 0) {
        getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                DuoDrawerLayout.this.getViewTreeObserver().removeOnPreDrawListener(this);
                if (mViewDragHelper.smoothSlideViewTo(mContentView, ((int) (getWidth() * mMarginFactor)), mContentView.getTop())) {
                    ViewCompat.postInvalidateOnAnimation(DuoDrawerLayout.this);
                }
                return false;
            }
        });
    } else {
        if (mViewDragHelper.smoothSlideViewTo(mContentView, drawerWidth, mContentView.getTop())) {
            ViewCompat.postInvalidateOnAnimation(DuoDrawerLayout.this);
        }
    }
}
 
Example #3
Source File: ItemTouchHelper.java    From Carbon with Apache License 2.0 6 votes vote down vote up
/**
 * Replaces a movement direction with its relative version by taking layout direction into
 * account.
 *
 * @param flags           The flag value that include any number of movement flags.
 * @param layoutDirection The layout direction of the View. Can be obtained from {@link
 *                        ViewCompat#getLayoutDirection(android.view.View)}.
 * @return Updated flags which uses relative flags ({@link #START}, {@link #END}) instead of
 * {@link #LEFT}, {@link #RIGHT}.
 * @see #convertToAbsoluteDirection(int, int)
 */
public static int convertToRelativeDirection(int flags, int layoutDirection) {
    int masked = flags & ABS_HORIZONTAL_DIR_FLAGS;
    if (masked == 0) {
        return flags; // does not have any abs flags, good.
    }
    flags &= ~masked; //remove left / right.
    if (layoutDirection == ViewCompat.LAYOUT_DIRECTION_LTR) {
        // no change. just OR with 2 bits shifted mask and return
        flags |= masked << 2; // START is 2 bits after LEFT, END is 2 bits after RIGHT.
        return flags;
    } else {
        // add RIGHT flag as START
        flags |= ((masked << 1) & ~ABS_HORIZONTAL_DIR_FLAGS);
        // first clean RIGHT bit then add LEFT flag as END
        flags |= ((masked << 1) & ABS_HORIZONTAL_DIR_FLAGS) << 2;
    }
    return flags;
}
 
Example #4
Source File: SubtitleCollapsingToolbarLayout.java    From collapsingtoolbarlayout-subtitle with Apache License 2.0 6 votes vote down vote up
@Override
protected void onAttachedToWindow() {
    super.onAttachedToWindow();

    // Add an OnOffsetChangedListener if possible
    final ViewParent parent = getParent();
    if (parent instanceof AppBarLayout) {
        // Copy over from the ABL whether we should fit system windows
        ViewCompat.setFitsSystemWindows(this, ViewCompat.getFitsSystemWindows((View) parent));

        if (onOffsetChangedListener == null) {
            onOffsetChangedListener = new OffsetUpdateListener();
        }
        ((AppBarLayout) parent).addOnOffsetChangedListener(onOffsetChangedListener);

        // We're attached, so lets request an inset dispatch
        ViewCompat.requestApplyInsets(this);
    }
}
 
Example #5
Source File: BaseDynamicCoordinatorLayoutTest.java    From material-components-android with Apache License 2.0 6 votes vote down vote up
protected ViewAction setLayoutDirection(final int layoutDir) {
  return new ViewAction() {
    @Override
    public Matcher<View> getConstraints() {
      return any(View.class);
    }

    @Override
    public String getDescription() {
      return "Sets layout direction";
    }

    @Override
    public void perform(UiController uiController, View view) {
      uiController.loopMainThreadUntilIdle();

      ViewCompat.setLayoutDirection(view, layoutDir);

      uiController.loopMainThreadUntilIdle();
    }
  };
}
 
Example #6
Source File: BaseSwitchButton.java    From switchbutton with MIT License 6 votes vote down vote up
/**
 * 移动手柄view
 *
 * @param delta 移动量
 */
protected final void moveView(int delta)
{
    if (delta == 0)
        return;

    final int current = mViewThumb.getLeft();
    final int min = getLeftNormal();
    final int max = getLeftChecked();
    delta = FTouchHelper.getLegalDelta(current, min, max, delta);

    if (delta == 0)
        return;

    ViewCompat.offsetLeftAndRight(mViewThumb, delta);
    notifyViewPositionChanged();
}
 
Example #7
Source File: DoubleHeaderDecoration.java    From header-decor with Apache License 2.0 6 votes vote down vote up
@Nullable
public View findHeaderViewUnder(float x, float y) {
    for (RecyclerView.ViewHolder holder : headerCache.values()) {
        final View child = holder.itemView;
        final float translationX = ViewCompat.getTranslationX(child);
        final float translationY = ViewCompat.getTranslationY(child);

        if (x >= child.getLeft() + translationX &&
                x <= child.getRight() + translationX &&
                y >= child.getTop() + translationY &&
                y <= child.getBottom() + translationY) {
            return child;
        }
    }

    return null;
}
 
Example #8
Source File: DynamicAppBarLayout.java    From dynamic-support with Apache License 2.0 6 votes vote down vote up
@Override
public void applyWindowInsets() {
    final int paddingTop = getPaddingTop();
    final int paddingLeft = getPaddingLeft();
    final int paddingRight = getPaddingRight();

    ViewCompat.setOnApplyWindowInsetsListener(this,
            new androidx.core.view.OnApplyWindowInsetsListener() {
        @Override
        public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
            v.setPadding(paddingLeft + insets.getSystemWindowInsetLeft(),
                    paddingTop + insets.getSystemWindowInsetTop(),
                    paddingRight + insets.getSystemWindowInsetRight(),
                    v.getPaddingBottom());

            return insets;
        }
    });
}
 
Example #9
Source File: ChipDrawable.java    From material-components-android with Apache License 2.0 6 votes vote down vote up
/** Calculates the chip text's origin and alignment based on the ChipDrawable-absolute bounds. */
@NonNull
Align calculateTextOriginAndAlignment(@NonNull Rect bounds, @NonNull PointF pointF) {
  pointF.set(0, 0);
  Align align = Align.LEFT;

  if (text != null) {
    float offsetFromStart = chipStartPadding + calculateChipIconWidth() + textStartPadding;

    if (DrawableCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_LTR) {
      pointF.x = bounds.left + offsetFromStart;
      align = Align.LEFT;
    } else {
      pointF.x = bounds.right - offsetFromStart;
      align = Align.RIGHT;
    }

    pointF.y = bounds.centerY() - calculateTextCenterFromBaseline();
  }

  return align;
}
 
Example #10
Source File: BottomSheetBehavior.java    From material-components-android with Apache License 2.0 6 votes vote down vote up
void startSettlingAnimation(View child, int state, int top, boolean settleFromViewDragHelper) {
  boolean startedSettling =
      settleFromViewDragHelper
          ? viewDragHelper.settleCapturedViewAt(child.getLeft(), top)
          : viewDragHelper.smoothSlideViewTo(child, child.getLeft(), top);
  if (startedSettling) {
    setStateInternal(STATE_SETTLING);
    // STATE_SETTLING won't animate the material shape, so do that here with the target state.
    updateDrawableForTargetState(state);
    if (settleRunnable == null) {
      // If the singleton SettleRunnable instance has not been instantiated, create it.
      settleRunnable = new SettleRunnable(child, state);
    }
    // If the SettleRunnable has not been posted, post it with the correct state.
    if (settleRunnable.isPosted == false) {
      settleRunnable.targetState = state;
      ViewCompat.postOnAnimation(child, settleRunnable);
      settleRunnable.isPosted = true;
    } else {
      // Otherwise, if it has been posted, just update the target state.
      settleRunnable.targetState = state;
    }
  } else {
    setStateInternal(state);
  }
}
 
Example #11
Source File: TabLayout.java    From a with GNU General Public License v3.0 6 votes vote down vote up
private void animateToTab(int newPosition) {
    if (newPosition == Tab.INVALID_POSITION) {
        return;
    }

    if (getWindowToken() == null || !ViewCompat.isLaidOut(this)
            || mTabStrip.childrenNeedLayout()) {
        // If we don't have a window token, or we haven't been laid out yet just draw the new
        // position now
        setScrollPosition(newPosition, 0f, true);
        return;
    }

    final int startScrollX = getScrollX();
    final int targetScrollX = calculateScrollXForTab(newPosition, 0);

    if (startScrollX != targetScrollX) {
        ensureScrollAnimator();

        mScrollAnimator.setIntValues(startScrollX, targetScrollX);
        mScrollAnimator.start();
    }

    // Now animate the indicator
    mTabStrip.animateIndicatorToPosition(newPosition, ANIMATION_DURATION);
}
 
Example #12
Source File: FadeInAnimator.java    From recyclerview-animators with Apache License 2.0 5 votes vote down vote up
@Override protected void animateRemoveImpl(final RecyclerView.ViewHolder holder) {
  ViewCompat.animate(holder.itemView)
      .alpha(0)
      .setDuration(getRemoveDuration())
      .setInterpolator(mInterpolator)
      .setListener(new DefaultRemoveVpaListener(holder))
      .setStartDelay(getRemoveDelay(holder))
      .start();
}
 
Example #13
Source File: ViewHelper.java    From recyclerview-animators with Apache License 2.0 5 votes vote down vote up
public static void clear(View v) {
  ViewCompat.setAlpha(v, 1);
  ViewCompat.setScaleY(v, 1);
  ViewCompat.setScaleX(v, 1);
  ViewCompat.setTranslationY(v, 0);
  ViewCompat.setTranslationX(v, 0);
  ViewCompat.setRotation(v, 0);
  ViewCompat.setRotationY(v, 0);
  ViewCompat.setRotationX(v, 0);
  ViewCompat.setPivotY(v, v.getMeasuredHeight() / 2);
  ViewCompat.setPivotX(v, v.getMeasuredWidth() / 2);
  ViewCompat.animate(v).setInterpolator(null).setStartDelay(0);
}
 
Example #14
Source File: ItemTouchUIUtilImpl.java    From monero-wallet-android-app with MIT License 5 votes vote down vote up
@Override
public void onDraw(Canvas c, RecyclerView recyclerView, View view,
                   float dX, float dY, int actionState, boolean isCurrentlyActive) {
    if (isCurrentlyActive) {
        Object originalElevation = view.getTag(R.id.item_touch_helper_previous_elevation);
        if (originalElevation == null) {
            originalElevation = ViewCompat.getElevation(view);
            float newElevation = 1f + findMaxElevation(recyclerView, view);
            ViewCompat.setElevation(view, newElevation);
            view.setTag(R.id.item_touch_helper_previous_elevation, originalElevation);
        }
    }
    super.onDraw(c, recyclerView, view, dX, dY, actionState, isCurrentlyActive);
}
 
Example #15
Source File: VerticalDividerItemDecoration.java    From DoraemonKit with Apache License 2.0 5 votes vote down vote up
@Override
protected Rect getDividerBound(int position, RecyclerView parent, View child) {
    Rect bounds = new Rect(0, 0, 0, 0);
    int transitionX = (int) ViewCompat.getTranslationX(child);
    int transitionY = (int) ViewCompat.getTranslationY(child);
    RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
    bounds.top = child.getTop() + transitionY;
    bounds.bottom = child.getBottom() + transitionY;

    int dividerSize = getDividerSize(position, parent);
    if (mDividerType == DividerType.DRAWABLE || mDividerType == DividerType.SPACE) {
        if (alignTopEdge(parent, position)) {
            bounds.top += mMarginProvider.dividerTopMargin(position, parent);
        }
        if (alignBottomEdge(parent, position)) {
            bounds.bottom -= mMarginProvider.dividerBottomMargin(position, parent);
        }

        bounds.left = child.getRight() + params.rightMargin + transitionX;
        bounds.right = bounds.left + dividerSize;
    } else {
        // set center point of divider
        int halfSize = dividerSize / 2;
        bounds.left = child.getRight() + params.rightMargin + halfSize + transitionX;
        bounds.right = bounds.left;
    }

    if (mPositionInsideItem) {
        bounds.left -= dividerSize;
        bounds.right -= dividerSize;
    }

    return bounds;
}
 
Example #16
Source File: SetupStepIndicatorView.java    From openboard with GNU General Public License v3.0 5 votes vote down vote up
public void setIndicatorPosition(final int stepPos, final int totalStepNum) {
    final int layoutDirection = ViewCompat.getLayoutDirection(this);
    // The indicator position is the center of the partition that is equally divided into
    // the total step number.
    final float partionWidth = 1.0f / totalStepNum;
    final float pos = stepPos * partionWidth + partionWidth / 2.0f;
    mXRatio = (layoutDirection == ViewCompat.LAYOUT_DIRECTION_RTL) ? 1.0f - pos : pos;
    invalidate();
}
 
Example #17
Source File: MedicineActivity.java    From Medicine-Time- with Apache License 2.0 5 votes vote down vote up
@OnClick(R.id.date_picker_button)
void onDatePickerButtonClicked() {
    if (isExpanded) {
        ViewCompat.animate(arrow).rotation(0).start();
    } else {
        ViewCompat.animate(arrow).rotation(180).start();
    }

    isExpanded = !isExpanded;
    appBarLayout.setExpanded(isExpanded, true);
}
 
Example #18
Source File: AppBarLayout.java    From material-components-android with Apache License 2.0 5 votes vote down vote up
/** Return the scroll range when scrolling down from a nested scroll. */
int getDownNestedScrollRange() {
  if (downScrollRange != INVALID_SCROLL_RANGE) {
    // If we already have a valid value, return it
    return downScrollRange;
  }

  int range = 0;
  for (int i = 0, z = getChildCount(); i < z; i++) {
    final View child = getChildAt(i);
    final LayoutParams lp = (LayoutParams) child.getLayoutParams();
    int childHeight = child.getMeasuredHeight();
    childHeight += lp.topMargin + lp.bottomMargin;

    final int flags = lp.scrollFlags;

    if ((flags & LayoutParams.SCROLL_FLAG_SCROLL) != 0) {
      // We're set to scroll so add the child's height
      range += childHeight;

      if ((flags & LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED) != 0) {
        // For a collapsing exit scroll, we to take the collapsed height into account.
        // We also break the range straight away since later views can't scroll
        // beneath us
        range -= ViewCompat.getMinimumHeight(child);
        break;
      }
    } else {
      // As soon as a view doesn't have the scroll flag, we end the range calculation.
      // This is because views below can not scroll under a fixed view.
      break;
    }
  }
  return downScrollRange = Math.max(0, range);
}
 
Example #19
Source File: ViewHelper.java    From PictureSelector with Apache License 2.0 5 votes vote down vote up
public static void clear(View v) {
    v.setAlpha(1);
    v.setScaleY(1);
    v.setScaleX(1);
    v.setTranslationY(0);
    v.setTranslationX(0);
    v.setRotation(0);
    v.setRotationY(0);
    v.setRotationX(0);
    v.setPivotY(v.getMeasuredHeight() / 2);
    v.setPivotX(v.getMeasuredWidth() / 2);
    ViewCompat.animate(v).setInterpolator(null).setStartDelay(0);
}
 
Example #20
Source File: DynamicFABScrollBehavior.java    From dynamic-support with Apache License 2.0 5 votes vote down vote up
@Override
public boolean onStartNestedScroll(@NonNull CoordinatorLayout coordinatorLayout,
        @NonNull View child, @NonNull View directTargetChild,
        @NonNull View target, int nestedScrollAxes, final int type) {
    // Ensure we react to vertical scrolling.
    return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL
            || super.onStartNestedScroll(coordinatorLayout, child,
            directTargetChild, target, nestedScrollAxes, type);
}
 
Example #21
Source File: MountState.java    From litho with Apache License 2.0 5 votes vote down vote up
private static void unsetAccessibilityDelegate(View view) {
  if (!(view instanceof ComponentHost) && view.getTag(R.id.component_node_info) == null) {
    return;
  }
  view.setTag(R.id.component_node_info, null);
  if (!(view instanceof ComponentHost)) {
    ViewCompat.setAccessibilityDelegate(view, null);
  }
}
 
Example #22
Source File: ScrollChildSwipeRefreshLayout.java    From simple-stack with Apache License 2.0 5 votes vote down vote up
@Override
public boolean canChildScrollUp() {
    if (mScrollUpChild != null) {
        return ViewCompat.canScrollVertically(mScrollUpChild, -1);
    }
    return super.canChildScrollUp();
}
 
Example #23
Source File: EasyRefreshLayout.java    From DoraemonKit with Apache License 2.0 5 votes vote down vote up
private boolean canChildScrollUp() {
    if (android.os.Build.VERSION.SDK_INT < 14) {
        if (contentView instanceof AbsListView) {
            final AbsListView absListView = (AbsListView) contentView;
            return absListView.getChildCount() > 0
                    && (absListView.getFirstVisiblePosition() > 0 || absListView.getChildAt(0)
                    .getTop() < absListView.getPaddingTop());
        } else {
            return ViewCompat.canScrollVertically(contentView, -1) || contentView.getScrollY() > 0;
        }
    } else {
        /*return true can  swipe up*/
        return ViewCompat.canScrollVertically(contentView, -1);
    }
}
 
Example #24
Source File: IndicatorViewController.java    From material-components-android with Apache License 2.0 5 votes vote down vote up
/**
 * Check if the caption view should animate. Only animate the caption view if we're enabled, laid
 * out, and have a different caption message.
 *
 * @param captionView The view that contains text for the caption underneath the text input area
 * @param captionText The text for the caption view
 * @return Whether the view should animate when setting the caption
 */
private boolean shouldAnimateCaptionView(
    @Nullable TextView captionView, @Nullable final CharSequence captionText) {
  return ViewCompat.isLaidOut(textInputView)
      && textInputView.isEnabled()
      && (captionToShow != captionDisplayed
          || captionView == null
          || !TextUtils.equals(captionView.getText(), captionText));
}
 
Example #25
Source File: FadeInLeftAnimator.java    From recyclerview-animators with Apache License 2.0 5 votes vote down vote up
@Override protected void animateAddImpl(final RecyclerView.ViewHolder holder) {
  ViewCompat.animate(holder.itemView)
      .translationX(0)
      .alpha(1)
      .setDuration(getAddDuration())
      .setInterpolator(mInterpolator)
      .setListener(new DefaultAddVpaListener(holder))
      .setStartDelay(getAddDelay(holder))
      .start();
}
 
Example #26
Source File: ParallaxScrimageView.java    From ShrinkingImageLayout with Apache License 2.0 5 votes vote down vote up
public void setOffset(float offset) {
    offset = Math.max(minOffset, offset);
    if (offset != getTranslationY()) {
        setTranslationY(offset);
        imageOffset = (int) (offset * parallaxFactor);
        setScrimAlpha(Math.min((-offset / getMinimumHeight()) * maxScrimAlpha, maxScrimAlpha));
        ViewCompat.postInvalidateOnAnimation(this);
    }
    setPinned(offset == minOffset);
}
 
Example #27
Source File: DynamicReboundSmoothRefreshLayout.java    From SmoothRefreshLayout with MIT License 5 votes vote down vote up
@Override
void stop() {
    if (mMode != Constants.SCROLLER_MODE_NONE) {
        if (sDebug) {
            Log.d(TAG, "ScrollChecker: stop()");
        }
        if (mNestedScrolling && isCalcFling()) {
            mMode = Constants.SCROLLER_MODE_NONE;
            stopNestedScroll(ViewCompat.TYPE_NON_TOUCH);
        } else {
            mMode = Constants.SCROLLER_MODE_NONE;
        }
        mAutomaticActionUseSmoothScroll = false;
        mIsScrolling = false;
        mScroller.forceFinished(true);
        if (mFlingAnimation != null) {
            mFlingAnimation.cancel();
        }
        if (mSpringAnimation != null) {
            mSpringAnimation.cancel();
        }
        mDuration = 0;
        mLastY = 0;
        mLastTo = -1;
        mLastStart = 0;
        removeCallbacks(this);
    }
}
 
Example #28
Source File: FadeInRightAnimator.java    From recyclerview-animators with Apache License 2.0 5 votes vote down vote up
@Override protected void animateAddImpl(final RecyclerView.ViewHolder holder) {
  ViewCompat.animate(holder.itemView)
      .translationX(0)
      .alpha(1)
      .setDuration(getAddDuration())
      .setInterpolator(mInterpolator)
      .setListener(new DefaultAddVpaListener(holder))
      .setStartDelay(getAddDelay(holder))
      .start();
}
 
Example #29
Source File: InputPanel.java    From deltachat-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onRecordMoved(float x, float absoluteX) {
  slideToCancel.moveTo(x);

  int   direction = ViewCompat.getLayoutDirection(this);
  float position  = absoluteX / recordingContainer.getWidth();

  if (direction == ViewCompat.LAYOUT_DIRECTION_LTR && position <= 0.5 ||
          direction == ViewCompat.LAYOUT_DIRECTION_RTL && position >= 0.6)
  {
    this.microphoneRecorderView.cancelAction();
  }
}
 
Example #30
Source File: SlidingUpPanelLayout.java    From react-native-photo-editor with Apache License 2.0 5 votes vote down vote up
@Override
public void computeScroll() {
    if (mDragHelper != null && mDragHelper.continueSettling(true)) {
        if (!isEnabled()) {
            mDragHelper.abort();
            return;
        }

        ViewCompat.postInvalidateOnAnimation(this);
    }
}