Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Animate a view using ObjectAnimator from left-to-right upto half of screen and inverse (right-to-left)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/sms_linear_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/img_android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher" />
</LinearLayout>
package com.pavneet.myapplication;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.graphics.Point;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Display;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
/**
* Created by Pavneet Singh on 9/20/2016.
* Email pavneet.edu@gmail.com
*/
public class MainActivity extends AppCompatActivity {
private ObjectAnimator lftToRgt,rgtToLft;
private ImageView imageView;
private float halfW;
private AnimatorSet animatorSet;//required to set the sequence
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
Display display = getWindowManager().getDefaultDisplay();
Point point=new Point();
display.getSize(point);
final int width = point.x; // screen width
halfW = width/2.0f; // half the width or to any value required,global to class
initializeUI();
}
void initializeUI(){
imageView = (ImageView) findViewById(R.id.img_android);
animatorSet = new AnimatorSet();
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
anim();// call to animate function
}
});
}
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.play( lftToRgt ).before( rgtToLft ); // manage sequence
animatorSet.start(); // play the animation
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment