Tuesday, July 7, 2015

How to animate X position of a View using ObjectAnimator in Android

MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.animation.ObjectAnimator;

public class MainActivity extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btn = (Button) findViewById(R.id.btn);
        final TextView tv = (TextView) findViewById(R.id.tv);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Move the object at the X position 500
                ObjectAnimator anim = ObjectAnimator.ofFloat(tv,"x",500);
                anim.setDuration(5000); // duration 5 seconds
                anim.start();
            }
        });
   }
}
More android examples