为获得更好的结构,推荐使用显示屏幕宽度的动态方法
首先计算屏幕宽度来测量屏幕的一半
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
}
});
将以下功能添加到您的课程中并享受。
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
}
查看完整的代码片段