Search code examples
androidanimationviewsliding

Android independent animations


How to make two independent animations for the same view.

Scenario would be like:

View is sliding from left to right, and user might click back button which means that the same view should fade out during sliding animation.

I can't achieve this, because when I start fade-out animation, sliding is being interrupted and moved to it's final position.

AnimationSet is not an option in this situation I guess.


Solution

  • You can use ObjectAnimator for Android SDK 14+ or the library NineOldAndroids for below. Here is an example how it would look (a View sliding 300px to right and additionally fades out as soon as back is pressed)

    private Animator fadeOut;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final View view = findViewById(R.id.button);
    
        //we prepare the fadeOut-Animator to be started onBackPressed
        fadeOut = ObjectAnimator.ofFloat(view, View.ALPHA, 0);
        fadeOut.setDuration(1000);
    
        //we prepare and start the slide-Animator
        final Animator slide = ObjectAnimator.ofFloat(view, View.TRANSLATION_X,300);
        slide.setDuration(3000);
        slide.start();
    }
    
    @Override
    public void onBackPressed() {
        //super.onBackPressed();
        fadeOut.start();
    }
    

    *I don't recommend to do something else with the back-button than navigating back.