Android 属性动画左右移动

实现动画的左右移动,用到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>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值