实现动画的左右移动,用到ObjectAnimator这个属性,要实现这个动画就要先在xml定义一个按钮,如下所示,我用到了一个背景图片,让这个背景图片左右移动
<span style="font-size:12px;"><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:background="@drawable/ico"
/>
</RelativeLayout>
</span>
下面就写实现背景图片左右移动的代码:
<span style="font-size:12px;">package com.example.objectanimator;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.BounceInterpolator;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener{
private Button btn;
private ObjectAnimator animator;
private boolean isClick = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(this);
//动画开始
if (!isClick){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
animator = ObjectAnimator.ofFloat(btn, "translationX", 0.0f , 20, 0f , 0f);
animator.setDuration(1500);//动画时间
animator.setInterpolator(new BounceInterpolator());//实现反复移动的效果
animator.setRepeatCount(-1);//设置动画重复次数
animator.setStartDelay(1000);//设置动画延时执行
animator.start();//启动动画
}
}
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
isClick = true;
//动画结束
if ( null != animator){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
btn.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
animator.end();//动画结束
}
});
}
}
Toast.makeText(MainActivity.this, "停止动画", 0).show();
break;
default:
break;
}
}
}
</span>