android 组件动画移动后原位置不变的解决办法

在做项目的时候发现给一些组件添加了移动动画,并且动画完之后停止在动画之后的位置之后再去点击组件的时候就点不到了,但是点移动之前原来的位置是可以,

从网上查了一下,解决办法都是在动画完之后把LayoutParams重新设置一下,这里一定要注意,设置完之后一定要把动画再清除一下clearAnimation(),否则两个设置会叠加在一起:
        AnimatorSet animationSet = new AnimatorSet();

        ObjectAnimator animator = ObjectAnimator.ofFloat(mainLayout, "translationY", 0, 25);
        animationSet.playTogether(animator);

        animationSet.setDuration(300);
        animationSet.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mainLayout.getLayoutParams();
                params.topMargin = params.topMargin + 25;
                mainLayout.setLayoutParams(params);
                mainLayout.clearAnimation();
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        animationSet.start();




测试又发现一个问题,在2.3.3版本和此版本以下的版本移动之后都需要手动移动一下位置,但是4.x多的系统以经不需要再手动移动,所以在加一个判断,修改成如下:
        AnimatorSet animationSet = new AnimatorSet();

        ObjectAnimator animator = ObjectAnimator.ofFloat(mainLayout, "translationY", 0, 25);
        animationSet.playTogether(animator);

        animationSet.setDuration(300);
        if(Build.VERSION.SDK_INT<14) {  //低于android4以下的动画完之后手动调整位置
            animationSet.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mainLayout.getLayoutParams();
                    params.topMargin = params.topMargin + 25;
                    mainLayout.setLayoutParams(params);
                    mainLayout.clearAnimation();
                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
        }
        animationSet.start();

你可能感兴趣的:(android)