How to apply easing animation function on view in Android

后端 未结 5 2042
情深已故
情深已故 2020-12-14 04:11

I want to apply a translate animation on an Android view (button) using a custom interpolator where the easing function is:

         


        
5条回答
  •  失恋的感觉
    2020-12-14 04:53

    Here is another solution, made possible by a recent addition to android's support library: https://gist.github.com/ebabel/8ff41cad01e9ce1dd9ce

    and an example in use:

    public static void expand(final View v) {
        v.measure(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        final int targetHeight = v.getMeasuredHeight();
    
        if ( v.getHeight() != targetHeight ) {
            // Older versions of android (pre API 21) cancel animations for views with a height of 0 so use 1 instead.
            v.getLayoutParams().height = 1;
            v.setVisibility(View.VISIBLE);
    
    
            Animation a = new Animation() {
                @Override
                protected void applyTransformation(float interpolatedTime, Transformation t) {
                    v.getLayoutParams().height = interpolatedTime == 1
                            ? ViewGroup.LayoutParams.WRAP_CONTENT
                            : (int) (targetHeight * interpolatedTime);
                    v.requestLayout();
                }
    
                @Override
                public boolean willChangeBounds() {
                    return true;
                }
            };
    
            a.setInterpolator(EasingsConstants.easeInOutQuart);
            a.setDuration(computeDurationFromHeight(v));
            v.startAnimation(a);
        } else {
            Log.d("AnimationUtil", "expand Already expanded ");
        }
    }
    
    /**
     * 1dp/ms * multiplier
     */
    private static int computeDurationFromHeight(View v) {
        return (int) (v.getMeasuredHeight() / v.getContext().getResources().getDisplayMetrics().density) * DURATION_MULTIPLIER;
    }
    

提交回复
热议问题