Android - Change left margin using animation

后端 未结 4 987
别那么骄傲
别那么骄傲 2020-12-07 18:25

I am changing the left margin of an image view in the following manner :

ViewGroup.MarginLayoutParams layoutParams =         


        
4条回答
  •  清歌不尽
    2020-12-07 19:20

    The answer from user1991679 is great, but if you need to interpolate a margin from any other value but 0, you need to use it in your calculations:

    ViewGroup.MarginLayoutParams params = (MarginLayoutParams) mBottomLayout.getLayoutParams();
    final int bottomMarginStart = params.bottomMargin; // your start value
    final int bottomMarginEnd = ; // where to animate to
    Animation a = new Animation() {
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            ViewGroup.MarginLayoutParams params = (MarginLayoutParams) mBottomLayout.getLayoutParams();
            // interpolate the proper value
            params.bottomMargin = bottomMarginStart + (int) ((bottomMarginEnd - bottomMarginStart) * interpolatedTime);
            mBottomLayout.setLayoutParams(params);
        }
    };
    a.setDuration(300);
    mBottomLayout.startAnimation(a);
    

    In my case I needed to animate an "enter the screen" animation, coming from "-48dp" to 0. Without the start value, the animation is always 0, thus jumping, not animating the view. The solution was to interpolate the offset and add it to the original value.

提交回复
热议问题