Android: Animation Position Resets After Complete

后端 未结 9 1543
南笙
南笙 2020-11-27 13:30

I\'m using an xml defined animation to slide a view off the screen. The problem is, as soon as the animation completes it resets to its original position. I need to know how

9条回答
  •  旧时难觅i
    2020-11-27 13:44

    Finally got a way to work around,the right way to do this is setFillAfter(true),

    if you want to define your animation in xml then you should do some thing like this

    
    
        
    
    
    

    you can see that i have defined filterAfter="true" in the set tag,if you try to define it in translate tag it won't work,might be a bug in the framework!!

    and then in the Code

    Animation anim = AnimationUtils.loadAnimation(this, R.anim.slide_out);
    someView.startAnimation(anim);
    

    OR

    TranslateAnimation animation = new TranslateAnimation(-90, 150, 0, 0);
    
    animation.setFillAfter(true);
    
    animation.setDuration(1800);
    
    someView.startAnimation(animation);
    

    then it will surely work!!

    Now this is a bit tricky it seems like the view is actually move to the new position but actually the pixels of the view are moved,i.e your view is actually at its initial position but not visible,you can test it if have you some button or clickable view in your view(in my case in layout),to fix that you have to manually move your view/layout to the new position

    public TranslateAnimation (float fromXDelta, float toXDelta, float fromYDelta, float toYDelta)
    
    new TranslateAnimation(-90, 150, 0, 0);
    

    now as we can see that our animation will starts from -90 x-axis to 150 x-axis

    so what we do is set

    someView.setAnimationListener(this);
    

    and in

    public void onAnimationEnd(Animation animation)
    {
       someView.layout(150, 0, someView.getWidth() + 150, someView.getHeight());
    }
    

    now let me explain public void layout (int left, int top, int right, int botton)

    it moves your layout to new position first argument define the left,which we is 150,because translate animation has animated our view to 150 x-axis, top is 0 because we haven't animated y-axis,now in right we have done someView.getWidth() + 150 basically we get the width of our view and added 150 because we our left is now move to 150 x-axis to make the view width to its originall one, and bottom is equals to the height of our view.

    I hope you people now understood the concept of translating, and still you have any questions you can ask right away in comment section,i feel pleasure to help :)

    EDIT Don't use layout() method as it can be called by the framework when ever view is invalidated and your changes won't presist, use LayoutParams to set your layout parameters according to your requirement

提交回复
热议问题