Example usage for android.animation AnimatorSet setDuration

List of usage examples for android.animation AnimatorSet setDuration

Introduction

In this page you can find the example usage for android.animation AnimatorSet setDuration.

Prototype

@Override
public AnimatorSet setDuration(long duration) 

Source Link

Document

Sets the length of each of the current child animations of this AnimatorSet.

Usage

From source file:com.b44t.ui.ActionBar.BottomSheet.java

public void dismissWithButtonClick(final int item) {
    if (dismissed) {
        return;//w w w  .j av a 2s . com
    }
    dismissed = true;
    cancelSheetAnimation();
    AnimatorSet animatorSet = new AnimatorSet();
    animatorSet.playTogether(
            ObjectAnimator.ofFloat(containerView, "translationY",
                    containerView.getMeasuredHeight() + AndroidUtilities.dp(10)),
            ObjectAnimator.ofInt(backDrawable, "alpha", 0));
    animatorSet.setDuration(180);
    animatorSet.setInterpolator(new AccelerateInterpolator());
    animatorSet.addListener(new AnimatorListenerAdapterProxy() {
        @Override
        public void onAnimationEnd(Animator animation) {
            if (currentSheetAnimation != null && currentSheetAnimation.equals(animation)) {
                currentSheetAnimation = null;
                if (onClickListener != null) {
                    onClickListener.onClick(BottomSheet.this, item);
                }
                AndroidUtilities.runOnUIThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            BottomSheet.super.dismiss();
                        } catch (Exception e) {
                            FileLog.e("messenger", e);
                        }
                    }
                });
            }
        }

        @Override
        public void onAnimationCancel(Animator animation) {
            if (currentSheetAnimation != null && currentSheetAnimation.equals(animation)) {
                currentSheetAnimation = null;
            }
        }
    });
    animatorSet.start();
    currentSheetAnimation = animatorSet;
}

From source file:com.flexible.flexibleadapter.AnimatorAdapter.java

/**
 * Performs checks to scroll animate the itemView and in case, it animates the view.
 * <p><b>Note:</b> If you have to change at runtime the LayoutManager <i>and</i> add
 * Scrollable Headers too, consider to add them in post, using a {@code delay >= 0},
 * otherwise scroll animations on all items will not start correctly.</p>
 *
 * @param holder   the ViewHolder just bound
 * @param position the current item position
 *///from   w  ww  .  j av a2 s. c  o m
@SuppressWarnings("ConstantConditions")
protected final void animateView(final RecyclerView.ViewHolder holder, final int position) {
    if (mRecyclerView == null)
        return;

    // Use always the max child count reached
    if (mMaxChildViews < mRecyclerView.getChildCount()) {
        mMaxChildViews = mRecyclerView.getChildCount();
    }
    // Animate only during initial loading?
    if (onlyEntryAnimation && mLastAnimatedPosition >= mMaxChildViews) {
        shouldAnimate = false;
    }
    int lastVisiblePosition = Utils.findLastVisibleItemPosition(mRecyclerView.getLayoutManager());
    //      if (DEBUG) {
    //         Log.v(TAG, "shouldAnimate=" + shouldAnimate
    //               + " isFastScroll=" + isFastScroll
    //               + " isNotified=" + mAnimatorNotifierObserver.isPositionNotified()
    //               + " isReverseEnabled=" + isReverseEnabled
    //               + " mLastAnimatedPosition=" + mLastAnimatedPosition
    //               + (!isReverseEnabled ? " Pos>LasVisPos=" + (position > lastVisiblePosition) : "")
    //               + " mMaxChildViews=" + mMaxChildViews
    //         );
    //      }
    if (holder instanceof FlexibleViewHolder && shouldAnimate && !isFastScroll
            && !mAnimatorNotifierObserver.isPositionNotified()
            && (position > lastVisiblePosition || isReverseEnabled || isScrollableHeaderOrFooter(position)
                    || (position == 0 && mMaxChildViews == 0))) {

        // Cancel animation is necessary when fling
        int hashCode = holder.itemView.hashCode();
        cancelExistingAnimation(hashCode);

        // User animators
        List<Animator> animators = new ArrayList<>();
        FlexibleViewHolder flexibleViewHolder = (FlexibleViewHolder) holder;
        flexibleViewHolder.scrollAnimators(animators, position, position >= lastVisiblePosition);

        // Execute the animations together
        AnimatorSet set = new AnimatorSet();
        set.playTogether(animators);
        set.setInterpolator(mInterpolator);
        // Single view duration
        long duration = mDuration;
        for (Animator animator : animators) {
            if (animator.getDuration() != DEFAULT_DURATION) {
                duration = animator.getDuration();
            }
        }
        //Log.v(TAG, "duration=" + duration);
        set.setDuration(duration);
        set.addListener(new HelperAnimatorListener(hashCode));
        if (mEntryStep) {
            // Stop stepDelay when screen is filled
            set.setStartDelay(calculateAnimationDelay(position));
        }
        set.start();
        mAnimators.put(hashCode, set);
        if (DEBUG)
            Log.v(TAG, "animateView    Scroll animation on position " + position);
    }
    mAnimatorNotifierObserver.clearNotified();
    // Update last animated position
    mLastAnimatedPosition = position;
}

From source file:com.pitchedapps.primenumbercalculator.Calculator.java

License:asdf

@Override
public void onTextSizeChanged(final TextView textView, float oldSize) {
    if (mCurrentState != CalculatorState.INPUT) {
        // Only animate text changes that occur from user input.
        return;/*  w w  w .  j  ava 2  s  . c  om*/
    }

    // Calculate the values needed to perform the scale and translation animations,
    // maintaining the same apparent baseline for the displayed text.
    final float textScale = oldSize / textView.getTextSize();
    final float translationX = (1.0f - textScale) * (textView.getWidth() / 2.0f - textView.getPaddingEnd());
    final float translationY = (1.0f - textScale) * (textView.getHeight() / 2.0f - textView.getPaddingBottom());

    final AnimatorSet animatorSet = new AnimatorSet();
    animatorSet.playTogether(ObjectAnimator.ofFloat(textView, View.SCALE_X, textScale, 1.0f),
            ObjectAnimator.ofFloat(textView, View.SCALE_Y, textScale, 1.0f),
            ObjectAnimator.ofFloat(textView, View.TRANSLATION_X, translationX, 0.0f),
            ObjectAnimator.ofFloat(textView, View.TRANSLATION_Y, translationY, 0.0f));
    animatorSet.setDuration(getResources().getInteger(android.R.integer.config_mediumAnimTime));
    animatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
    animatorSet.start();
}

From source file:com.hannesdorfmann.search.SearchActivity.java

@Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_search);
      setRetainInstance(true);//ww  w .ja v a 2s . c  o m

      ButterKnife.bind(this);
      setupSearchView();

      auto = TransitionInflater.from(this).inflateTransition(R.transition.auto);
      adapter = new FeedAdapter(this, columns, PocketUtils.isPocketInstalled(this));

      results.setAdapter(adapter);
      GridLayoutManager layoutManager = new GridLayoutManager(this, columns);
      layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
          @Override
          public int getSpanSize(int position) {
              return adapter.getItemColumnSpan(position);
          }
      });
      results.setLayoutManager(layoutManager);
      results.addOnScrollListener(new InfiniteScrollListener(layoutManager) {
          @Override
          public void onLoadMore() {
              if (!adapter.isLoadingMore()) {
                  presenter.searchMore(searchView.getQuery().toString());
              }
          }
      });
      results.setHasFixedSize(true);
      results.addOnScrollListener(gridScroll);

      // extract the search icon's location passed from the launching activity, minus 4dp to
      // compensate for different paddings in the views
      searchBackDistanceX = getIntent().getIntExtra(EXTRA_MENU_LEFT, 0) - (int) TypedValue
              .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources().getDisplayMetrics());
      searchIconCenterX = getIntent().getIntExtra(EXTRA_MENU_CENTER_X, 0);

      // translate icon to match the launching screen then animate back into position
      searchBackContainer.setTranslationX(searchBackDistanceX);
      searchBackContainer.animate().translationX(0f).setDuration(650L)
              .setInterpolator(AnimationUtils.loadInterpolator(this, android.R.interpolator.fast_out_slow_in));
      // transform from search icon to back icon
      AnimatedVectorDrawable searchToBack = (AnimatedVectorDrawable) ContextCompat.getDrawable(this,
              R.drawable.avd_search_to_back);
      searchBack.setImageDrawable(searchToBack);
      searchToBack.start();
      // for some reason the animation doesn't always finish (leaving a part arrow!?) so after
      // the animation set a static drawable. Also animation callbacks weren't added until API23
      // so using post delayed :(
      // TODO fix properly!!
      searchBack.postDelayed(new Runnable() {
          @Override
          public void run() {
              searchBack.setImageDrawable(
                      ContextCompat.getDrawable(SearchActivity.this, R.drawable.ic_arrow_back_padded));
          }
      }, 600);

      // fade in the other search chrome
      searchBackground.animate().alpha(1f).setDuration(300L)
              .setInterpolator(AnimationUtils.loadInterpolator(this, android.R.interpolator.linear_out_slow_in));
      searchView.animate().alpha(1f).setStartDelay(400L).setDuration(400L)
              .setInterpolator(AnimationUtils.loadInterpolator(this, android.R.interpolator.linear_out_slow_in))
              .setListener(new AnimatorListenerAdapter() {
                  @Override
                  public void onAnimationEnd(Animator animation) {
                      searchView.requestFocus();
                      ImeUtils.showIme(searchView);
                  }
              });

      // animate in a scrim over the content behind
      scrim.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
          @Override
          public boolean onPreDraw() {
              scrim.getViewTreeObserver().removeOnPreDrawListener(this);
              AnimatorSet showScrim = new AnimatorSet();
              showScrim.playTogether(
                      ViewAnimationUtils.createCircularReveal(scrim, searchIconCenterX,
                              searchBackground.getBottom(), 0,
                              (float) Math.hypot(searchBackDistanceX,
                                      scrim.getHeight() - searchBackground.getBottom())),
                      ObjectAnimator.ofArgb(scrim, ViewUtils.BACKGROUND_COLOR, Color.TRANSPARENT,
                              ContextCompat.getColor(SearchActivity.this, R.color.scrim)));
              showScrim.setDuration(400L);
              showScrim.setInterpolator(AnimationUtils.loadInterpolator(SearchActivity.this,
                      android.R.interpolator.linear_out_slow_in));
              showScrim.start();
              return false;
          }
      });
      onNewIntent(getIntent());
  }

From source file:org.michaelbel.bottomsheet.BottomSheet.java

private void startOpenAnimation() {
    containerView.setVisibility(View.VISIBLE);

    if (Build.VERSION.SDK_INT >= 20) {
        container.setLayerType(View.LAYER_TYPE_HARDWARE, null);
    }/*from   w w  w .  j av  a  2s.co m*/

    containerView.setTranslationY(containerView.getMeasuredHeight());
    AnimatorSet animatorSet = new AnimatorSet();
    animatorSet.playTogether(ObjectAnimator.ofFloat(containerView, "translationY", 0),
            ObjectAnimator.ofInt(backDrawable, "alpha", 51));
    animatorSet.setDuration(200);
    animatorSet.setStartDelay(20);
    animatorSet.setInterpolator(new DecelerateInterpolator());
    animatorSet.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            super.onAnimationEnd(animation);
            if (currentSheetAnimation != null && currentSheetAnimation.equals(animation)) {
                currentSheetAnimation = null;
                container.setLayerType(View.LAYER_TYPE_NONE, null);
            }
        }

        @Override
        public void onAnimationCancel(Animator animation) {
            super.onAnimationCancel(animation);
            if (currentSheetAnimation != null && currentSheetAnimation.equals(animation)) {
                currentSheetAnimation = null;
            }
        }
    });
    animatorSet.start();
    currentSheetAnimation = animatorSet;
}

From source file:babbq.com.searchplace.SearchActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search);
    ButterKnife.bind(this);
    setupSearchView();//from  w  w w.ja  v  a2 s.c  om
    auto = TransitionInflater.from(this).inflateTransition(R.transition.auto);

    mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(LocationServices.API)
            .addApi(Places.GEO_DATA_API).addConnectionCallbacks(this).addOnConnectionFailedListener(this)
            .build();

    mAdapter = new TestAdapter(null, v -> {
        int position = results.getChildLayoutPosition(v);
        //Toast.makeText(getActivity(), "#" + position, Toast.LENGTH_SHORT).show();
        PendingResult result = Places.GeoDataApi.getPlaceById(mGoogleApiClient,
                String.valueOf(mAdapter.getElementAt(position).placeId));
        result.setResultCallback(mCoordinatePlaceDetailsCallback);
    }, mGoogleApiClient);

    dataManager = new SearchDataManager(mGoogleApiClient, mCoordinatePlaceDetailsCallback) {

        @Override
        public void onDataLoaded(List<? extends PlaceAutocomplete> data) {
            if (data != null && data.size() > 0) {
                if (results.getVisibility() != View.VISIBLE) {
                    TransitionManager.beginDelayedTransition(container, auto);
                    progress.setVisibility(View.GONE);
                    results.setVisibility(View.VISIBLE);
                    //                        fab.setVisibility(View.VISIBLE);
                    fab.setAlpha(0.6f);
                    fab.setScaleX(0f);
                    fab.setScaleY(0f);
                    fab.animate().alpha(1f).scaleX(1f).scaleY(1f).setStartDelay(800L).setDuration(300L)
                            .setInterpolator(AnimationUtils.loadInterpolator(SearchActivity.this,
                                    android.R.interpolator.linear_out_slow_in));
                }
                //                    mAdapter.addAndResort(data);
                mAdapter.setList(data);
            } else {
                TransitionManager.beginDelayedTransition(container, auto);
                progress.setVisibility(View.GONE);
                setNoResultsVisibility(View.VISIBLE);
            }
        }
    };
    //        mAdapter = new FeedAdapter(this, dataManager, columns);
    results.setAdapter(mAdapter);
    GridLayoutManager layoutManager = new GridLayoutManager(this, columns);
    //        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
    //
    //            @Override
    //            public int getSpanSize(int position) {
    //                return mAdapter.getItemColumnSpan(position);
    //            }
    //        });
    results.setLayoutManager(layoutManager);
    results.addOnScrollListener(new InfiniteScrollListener(layoutManager, dataManager) {

        @Override
        public void onLoadMore() {
            dataManager.loadMore();
        }
    });
    results.setHasFixedSize(true);
    results.addOnScrollListener(gridScroll);

    // extract the search icon's location passed from the launching activity, minus 4dp to
    // compensate for different paddings in the views
    searchBackDistanceX = getIntent().getIntExtra(EXTRA_MENU_LEFT, 0) - (int) TypedValue
            .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources().getDisplayMetrics());
    searchIconCenterX = getIntent().getIntExtra(EXTRA_MENU_CENTER_X, 0);

    // translate icon to match the launching screen then animate back into position
    searchBackContainer.setTranslationX(searchBackDistanceX);
    searchBackContainer.animate().translationX(0f).setDuration(650L)
            .setInterpolator(AnimationUtils.loadInterpolator(this, android.R.interpolator.fast_out_slow_in));
    // transform from search icon to back icon
    AnimatedVectorDrawable searchToBack = (AnimatedVectorDrawable) ContextCompat.getDrawable(this,
            R.drawable.avd_search_to_back);
    searchBack.setImageDrawable(searchToBack);
    searchToBack.start();
    // for some reason the animation doesn't always finish (leaving a part arrow!?) so after
    // the animation set a static drawable. Also animation callbacks weren't added until API23
    // so using post delayed :(
    // TODO fix properly!!
    searchBack.postDelayed(new Runnable() {

        @Override
        public void run() {
            searchBack.setImageDrawable(
                    ContextCompat.getDrawable(SearchActivity.this, R.drawable.ic_arrow_back_padded));
        }
    }, 600);

    // fade in the other search chrome
    searchBackground.animate().alpha(1f).setDuration(300L)
            .setInterpolator(AnimationUtils.loadInterpolator(this, android.R.interpolator.linear_out_slow_in));
    searchView.animate().alpha(1f).setStartDelay(400L).setDuration(400L)
            .setInterpolator(AnimationUtils.loadInterpolator(this, android.R.interpolator.linear_out_slow_in))
            .setListener(new AnimatorListenerAdapter() {

                @Override
                public void onAnimationEnd(Animator animation) {
                    searchView.requestFocus();
                    ImeUtils.showIme(searchView);
                }
            });

    // animate in a scrim over the content behind
    scrim.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {

        @Override
        public boolean onPreDraw() {
            scrim.getViewTreeObserver().removeOnPreDrawListener(this);
            AnimatorSet showScrim = new AnimatorSet();
            showScrim.playTogether(
                    ViewAnimationUtils.createCircularReveal(scrim, searchIconCenterX,
                            searchBackground.getBottom(), 0,
                            (float) Math.hypot(searchBackDistanceX,
                                    scrim.getHeight() - searchBackground.getBottom())),
                    ObjectAnimator.ofArgb(scrim, ViewUtils.BACKGROUND_COLOR, Color.TRANSPARENT,
                            ContextCompat.getColor(SearchActivity.this, R.color.scrim)));
            showScrim.setDuration(400L);
            showScrim.setInterpolator(AnimationUtils.loadInterpolator(SearchActivity.this,
                    android.R.interpolator.linear_out_slow_in));
            showScrim.start();
            return false;
        }
    });
    onNewIntent(getIntent());
}

From source file:ir.besteveryeverapp.ui.ActionBar.BottomSheet.java

@Override
public void dismiss() {
    if (dismissed) {
        return;//from w ww  . j  av a2  s. c  om
    }
    dismissed = true;
    cancelSheetAnimation();
    if (!allowCustomAnimation || !onCustomCloseAnimation()) {
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(
                ObjectAnimator.ofFloat(containerView, "translationY",
                        containerView.getMeasuredHeight() + AndroidUtilities.dp(10)),
                ObjectAnimator.ofInt(backDrawable, "alpha", 0));
        if (useFastDismiss) {
            int height = containerView.getMeasuredHeight();
            animatorSet.setDuration(
                    Math.max(60, (int) (180 * (height - containerView.getTranslationY()) / (float) height)));
            useFastDismiss = false;
        } else {
            animatorSet.setDuration(180);
        }
        animatorSet.setInterpolator(new AccelerateInterpolator());
        animatorSet.addListener(new AnimatorListenerAdapterProxy() {
            @Override
            public void onAnimationEnd(Animator animation) {
                if (currentSheetAnimation != null && currentSheetAnimation.equals(animation)) {
                    currentSheetAnimation = null;
                    AndroidUtilities.runOnUIThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                dismissInternal();
                            } catch (Exception e) {
                                FileLog.e("tmessages", e);
                            }
                        }
                    });
                }
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                if (currentSheetAnimation != null && currentSheetAnimation.equals(animation)) {
                    currentSheetAnimation = null;
                }
            }
        });
        animatorSet.start();
        currentSheetAnimation = animatorSet;
    }
}

From source file:com.b44t.ui.ActionBar.BottomSheet.java

@Override
public void dismiss() {
    if (dismissed) {
        return;/*from  ww w  .j  av  a 2  s. c om*/
    }
    dismissed = true;
    cancelSheetAnimation();
    if (!allowCustomAnimation || !onCustomCloseAnimation()) {
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(
                ObjectAnimator.ofFloat(containerView, "translationY",
                        containerView.getMeasuredHeight() + AndroidUtilities.dp(10)),
                ObjectAnimator.ofInt(backDrawable, "alpha", 0));
        if (useFastDismiss) {
            int height = containerView.getMeasuredHeight();
            animatorSet.setDuration(
                    Math.max(60, (int) (180 * (height - containerView.getTranslationY()) / (float) height)));
            useFastDismiss = false;
        } else {
            animatorSet.setDuration(180);
        }
        animatorSet.setInterpolator(new AccelerateInterpolator());
        animatorSet.addListener(new AnimatorListenerAdapterProxy() {
            @Override
            public void onAnimationEnd(Animator animation) {
                if (currentSheetAnimation != null && currentSheetAnimation.equals(animation)) {
                    currentSheetAnimation = null;
                    AndroidUtilities.runOnUIThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                dismissInternal();
                            } catch (Exception e) {
                                FileLog.e("messenger", e);
                            }
                        }
                    });
                }
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                if (currentSheetAnimation != null && currentSheetAnimation.equals(animation)) {
                    currentSheetAnimation = null;
                }
            }
        });
        animatorSet.start();
        currentSheetAnimation = animatorSet;
    }
}

From source file:org.telegram.ui.Components.StickersAlert.java

private void init(Context context) {
    shadowDrawable = context.getResources().getDrawable(R.drawable.sheet_shadow);

    containerView = new FrameLayout(context) {

        private int lastNotifyWidth;

        @Override//from  ww w.j  av  a 2s  .c  o m
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            if (ev.getAction() == MotionEvent.ACTION_DOWN && scrollOffsetY != 0 && ev.getY() < scrollOffsetY) {
                dismiss();
                return true;
            }
            return super.onInterceptTouchEvent(ev);
        }

        @Override
        public boolean onTouchEvent(MotionEvent e) {
            return !isDismissed() && super.onTouchEvent(e);
        }

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int height = MeasureSpec.getSize(heightMeasureSpec);
            if (Build.VERSION.SDK_INT >= 21) {
                height -= AndroidUtilities.statusBarHeight;
            }
            int contentSize;
            if (stickerSetCovereds != null) {
                contentSize = AndroidUtilities.dp(48 + 8) + AndroidUtilities.dp(60) * stickerSetCovereds.size()
                        + adapter.stickersRowCount * AndroidUtilities.dp(82);
            } else {
                contentSize = AndroidUtilities.dp(48 + 48) + Math.max(3,
                        (stickerSet != null ? (int) Math.ceil(stickerSet.documents.size() / 5.0f) : 0))
                        * AndroidUtilities.dp(82) + backgroundPaddingTop;
            }
            int padding = contentSize < (height / 5 * 3.2) ? 0 : (height / 5 * 2);
            if (padding != 0 && contentSize < height) {
                padding -= (height - contentSize);
            }
            if (padding == 0) {
                padding = backgroundPaddingTop;
            }
            if (stickerSetCovereds != null) {
                padding += AndroidUtilities.dp(8);
            }
            if (gridView.getPaddingTop() != padding) {
                ignoreLayout = true;
                gridView.setPadding(AndroidUtilities.dp(10), padding, AndroidUtilities.dp(10), 0);
                emptyView.setPadding(0, padding, 0, 0);
                ignoreLayout = false;
            }
            super.onMeasure(widthMeasureSpec,
                    MeasureSpec.makeMeasureSpec(Math.min(contentSize, height), MeasureSpec.EXACTLY));
        }

        @Override
        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
            if (lastNotifyWidth != right - left) {
                lastNotifyWidth = right - left;
                if (adapter != null && stickerSetCovereds != null) {
                    adapter.notifyDataSetChanged();
                }
            }
            super.onLayout(changed, left, top, right, bottom);
            updateLayout();
        }

        @Override
        public void requestLayout() {
            if (ignoreLayout) {
                return;
            }
            super.requestLayout();
        }

        @Override
        protected void onDraw(Canvas canvas) {
            shadowDrawable.setBounds(0, scrollOffsetY - backgroundPaddingTop, getMeasuredWidth(),
                    getMeasuredHeight());
            shadowDrawable.draw(canvas);
        }
    };
    containerView.setWillNotDraw(false);
    containerView.setPadding(backgroundPaddingLeft, 0, backgroundPaddingLeft, 0);

    titleTextView = new TextView(context);
    titleTextView.setLines(1);
    titleTextView.setSingleLine(true);
    titleTextView.setTextColor(
            ContextCompat.getColor(context, R.color.primary_text) /*Theme.STICKERS_SHEET_TITLE_TEXT_COLOR*/);
    titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
    titleTextView.setEllipsize(TextUtils.TruncateAt.MIDDLE);
    titleTextView.setPadding(AndroidUtilities.dp(18), 0, AndroidUtilities.dp(18), 0);
    titleTextView.setGravity(Gravity.CENTER_VERTICAL);
    titleTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    containerView.addView(titleTextView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48));
    titleTextView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }
    });

    shadow[0] = new View(context);
    shadow[0].setBackgroundResource(R.drawable.header_shadow);
    shadow[0].setAlpha(0.0f);
    shadow[0].setVisibility(View.INVISIBLE);
    shadow[0].setTag(1);
    containerView.addView(shadow[0],
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 3, Gravity.TOP | Gravity.LEFT, 0, 48, 0, 0));

    gridView = new RecyclerListView(context) {
        @Override
        public boolean onInterceptTouchEvent(MotionEvent event) {
            boolean result = StickerPreviewViewer.getInstance().onInterceptTouchEvent(event, gridView, 0);
            return super.onInterceptTouchEvent(event) || result;
        }

        @Override
        public void requestLayout() {
            if (ignoreLayout) {
                return;
            }
            super.requestLayout();
        }
    };
    gridView.setTag(14);
    gridView.setLayoutManager(layoutManager = new GridLayoutManager(getContext(), 5));
    layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {
            if (stickerSetCovereds != null && adapter.cache.get(position) instanceof Integer
                    || position == adapter.totalItems) {
                return adapter.stickersPerRow;
            }
            return 1;
        }
    });
    gridView.setAdapter(adapter = new GridAdapter(context));
    gridView.setVerticalScrollBarEnabled(false);
    gridView.addItemDecoration(new RecyclerView.ItemDecoration() {
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            outRect.left = 0;
            outRect.right = 0;
            outRect.bottom = 0;
            outRect.top = 0;
        }
    });
    gridView.setPadding(AndroidUtilities.dp(10), 0, AndroidUtilities.dp(10), 0);
    gridView.setClipToPadding(false);
    gridView.setEnabled(true);
    gridView.setGlowColor(0xfff5f6f7);
    gridView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return StickerPreviewViewer.getInstance().onTouch(event, gridView, 0, stickersOnItemClickListener);
        }
    });
    gridView.setOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            updateLayout();
        }
    });
    stickersOnItemClickListener = new RecyclerListView.OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {
            if (stickerSetCovereds != null) {
                TLRPC.StickerSetCovered pack = adapter.positionsToSets.get(position);
                if (pack != null) {
                    dismiss();
                    TLRPC.TL_inputStickerSetID inputStickerSetID = new TLRPC.TL_inputStickerSetID();
                    inputStickerSetID.access_hash = pack.set.access_hash;
                    inputStickerSetID.id = pack.set.id;
                    StickersAlert alert = new StickersAlert(parentActivity, parentFragment, inputStickerSetID,
                            null, null);
                    alert.show();
                }
            } else {
                if (stickerSet == null || position < 0 || position >= stickerSet.documents.size()) {
                    return;
                }
                selectedSticker = stickerSet.documents.get(position);

                boolean set = false;
                for (int a = 0; a < selectedSticker.attributes.size(); a++) {
                    TLRPC.DocumentAttribute attribute = selectedSticker.attributes.get(a);
                    if (attribute instanceof TLRPC.TL_documentAttributeSticker) {
                        if (attribute.alt != null && attribute.alt.length() > 0) {
                            stickerEmojiTextView.setText(Emoji.replaceEmoji(attribute.alt,
                                    stickerEmojiTextView.getPaint().getFontMetricsInt(),
                                    AndroidUtilities.dp(30), false));
                            set = true;
                        }
                        break;
                    }
                }
                if (!set) {
                    stickerEmojiTextView
                            .setText(Emoji.replaceEmoji(StickersQuery.getEmojiForSticker(selectedSticker.id),
                                    stickerEmojiTextView.getPaint().getFontMetricsInt(),
                                    AndroidUtilities.dp(30), false));
                }

                stickerImageView.getImageReceiver().setImage(selectedSticker, null,
                        selectedSticker.thumb.location, null, "webp", true);
                FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) stickerPreviewLayout
                        .getLayoutParams();
                layoutParams.topMargin = scrollOffsetY;
                stickerPreviewLayout.setLayoutParams(layoutParams);
                stickerPreviewLayout.setVisibility(View.VISIBLE);
                AnimatorSet animatorSet = new AnimatorSet();
                animatorSet.playTogether(ObjectAnimator.ofFloat(stickerPreviewLayout, "alpha", 0.0f, 1.0f));
                animatorSet.setDuration(200);
                animatorSet.start();
            }
        }
    };
    gridView.setOnItemClickListener(stickersOnItemClickListener);
    containerView.addView(gridView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, 0, 48, 0, 48));

    emptyView = new FrameLayout(context) {
        @Override
        public void requestLayout() {
            if (ignoreLayout) {
                return;
            }
            super.requestLayout();
        }
    };
    containerView.addView(emptyView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, 0, 0, 0, 48));
    gridView.setEmptyView(emptyView);
    emptyView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }
    });

    ProgressBar progressView = new ProgressBar(context);
    emptyView.addView(progressView,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));

    shadow[1] = new View(context);
    shadow[1].setBackgroundResource(R.drawable.header_shadow_reverse);
    containerView.addView(shadow[1],
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 3, Gravity.BOTTOM | Gravity.LEFT, 0, 0, 0, 48));

    pickerBottomLayout = new PickerBottomLayout(context, false);
    containerView.addView(pickerBottomLayout,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.LEFT | Gravity.BOTTOM));
    pickerBottomLayout.cancelButton.setPadding(AndroidUtilities.dp(18), 0, AndroidUtilities.dp(18), 0);
    pickerBottomLayout.cancelButton.setTextColor(Theme.STICKERS_SHEET_CLOSE_TEXT_COLOR);
    pickerBottomLayout.cancelButton.setText(LocaleController.getString("Close", R.string.Close).toUpperCase());
    pickerBottomLayout.cancelButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            dismiss();
        }
    });
    pickerBottomLayout.doneButton.setPadding(AndroidUtilities.dp(18), 0, AndroidUtilities.dp(18), 0);
    pickerBottomLayout.doneButtonBadgeTextView.setBackgroundResource(R.drawable.stickercounter);

    stickerPreviewLayout = new FrameLayout(context);
    if ((context.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_YES) != 0) {
        stickerPreviewLayout.setBackgroundColor(
                0x00ffffff & ContextCompat.getColor(context, R.color.card_background) | 0xdf000000);
    } else {
        stickerPreviewLayout.setBackgroundColor(0xdfffffff);
    }
    stickerPreviewLayout.setVisibility(View.GONE);
    stickerPreviewLayout.setSoundEffectsEnabled(false);
    containerView.addView(stickerPreviewLayout,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    stickerPreviewLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            hidePreview();
        }
    });

    ImageView closeButton = new ImageView(context);
    closeButton.setImageResource(R.drawable.delete_reply);
    closeButton.setScaleType(ImageView.ScaleType.CENTER);
    if (Build.VERSION.SDK_INT >= 21) {
        closeButton.setBackgroundDrawable(Theme.createBarSelectorDrawable(Theme.INPUT_FIELD_SELECTOR_COLOR));
    }
    stickerPreviewLayout.addView(closeButton, LayoutHelper.createFrame(48, 48, Gravity.RIGHT | Gravity.TOP));
    closeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            hidePreview();
        }
    });

    stickerImageView = new BackupImageView(context);
    stickerImageView.setAspectFit(true);
    stickerPreviewLayout.addView(stickerImageView);

    stickerEmojiTextView = new TextView(context);
    stickerEmojiTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 30);
    stickerEmojiTextView.setGravity(Gravity.BOTTOM | Gravity.RIGHT);
    stickerPreviewLayout.addView(stickerEmojiTextView);

    previewSendButton = new TextView(context);
    previewSendButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    previewSendButton.setTextColor(Theme.STICKERS_SHEET_SEND_TEXT_COLOR);
    previewSendButton.setGravity(Gravity.CENTER);
    previewSendButton.setBackgroundColor(ContextCompat.getColor(context, R.color.background));
    previewSendButton.setPadding(AndroidUtilities.dp(29), 0, AndroidUtilities.dp(29), 0);
    previewSendButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    stickerPreviewLayout.addView(previewSendButton,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.BOTTOM | Gravity.LEFT));
    previewSendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            delegate.onStickerSelected(selectedSticker);
            dismiss();
        }
    });

    previewSendButtonShadow = new View(context);
    previewSendButtonShadow.setBackgroundResource(R.drawable.header_shadow_reverse);
    stickerPreviewLayout.addView(previewSendButtonShadow,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 3, Gravity.BOTTOM | Gravity.LEFT, 0, 0, 0, 48));
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.emojiDidLoaded);

    updateFields();
    updateSendButton();
    adapter.notifyDataSetChanged();
}

From source file:org.michaelbel.bottomsheet.BottomSheet.java

private void dismissWithButtonClick(final int viewId) {
    if (dismissed) {
        return;/*from   w w  w .j  a  va  2 s  .  com*/
    }

    dismissed = true;
    cancelSheetAnimation();
    AnimatorSet animatorSet = new AnimatorSet();
    animatorSet.playTogether(
            ObjectAnimator.ofFloat(containerView, "translationY",
                    containerView.getMeasuredHeight() + Utils.dp(getContext(), 10)),
            ObjectAnimator.ofInt(backDrawable, "alpha", 0));
    animatorSet.setDuration(180);
    animatorSet.setInterpolator(new AccelerateInterpolator());
    animatorSet.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            super.onAnimationEnd(animation);
            if (currentSheetAnimation != null && currentSheetAnimation.equals(animation)) {
                currentSheetAnimation = null;
                if (onClickListener != null) {
                    onClickListener.onClick(BottomSheet.this, viewId);
                }

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            BottomSheet.super.dismiss();
                        } catch (Exception e) {
                            Log.e(TAG, e.getMessage());
                        }
                    }
                });
            }
        }

        @Override
        public void onAnimationCancel(Animator animation) {
            super.onAnimationCancel(animation);
            if (currentSheetAnimation != null && currentSheetAnimation.equals(animation)) {
                currentSheetAnimation = null;
            }
        }
    });

    animatorSet.start();
    currentSheetAnimation = animatorSet;

    if (bottomSheetCallBack != null) {
        bottomSheetCallBack.onClose();
    }
}