Search code examples
androidanimator

How to set animator for left to right and inverse for Multiple Screens


I want to make an animation for ImageView which runs from left to right on screen and when it reached to 50% of screen, it comes back. My XML:

<?xml version="1.0" encoding="utf-8"?>
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"

    android:duration="1000"
    android:propertyName="x"
    android:repeatMode="reverse"
    android:repeatCount="1"
    android:valueFrom="0"
    android:valueTo="250" >
</objectAnimator>

My application ran well on my phone but when it ran on a smaller or bigger phone, it didn't run well. I want to use ObjectAnimator and my application min SDK API is 13. Who can help me? Thanks in advance.


Solution

  • For better structure, a dynamic approach is recommended which uses display screen width

    First calculate the screen width to measure the half of the screen

        Display display = getWindowManager().getDefaultDisplay();
        Point point=new Point();
        display.getSize(point);
        final int width = point.x; // screen width
        final float halfW = width/2.0f; // half the width or to any value required,global to class
        ObjectAnimator lftToRgt,rgtToLft; // global to class
    
        // initialize the view in onCreate
        imageView = (ImageView) findViewById(R.id.imageButtontest);
    
        // set the click listener  
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                   anim();// call to animate
             }
         });
    

    Add the below function to your class and enjoy.

    void anim(){
        // translationX to move object along x axis
        // next values are position value
        lftToRgt = ObjectAnimator.ofFloat( imageView,"translationX",0f,halfW )
                .setDuration(700); // to animate left to right
        rgtToLft = ObjectAnimator.ofFloat( imageView,"translationX",halfW,0f )
                .setDuration(700); // to animate right to left
    
        AnimatorSet s = new AnimatorSet();//required to set the sequence
        s.play( lftToRgt ).before( rgtToLft ); // manage sequence
        s.start(); // play the animation
    }
    

    Check out the complete Code Snippet