整体很简单,直接上代码吧。activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<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="com.example.administrator.animator_demo2.MainActivity"> <Button
android:id="@+id/btn_click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Click" /> </RelativeLayout>
然后是JAVA代码,MainActivity.java:
package com.example.administrator.animator_demo2; import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button btn_click; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
} private void initView() {
btn_click = (Button) findViewById(R.id.btn_click);
btn_click.setOnClickListener(this);
} @Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_click:
// startAnimator1();
/**
* startAnimator1()方法当中,一下就重写了四个监听方法,在因为有的时候,我们
* 我们并不需要监听那么多,只需要其中的onAnimationEnd()方法。
* 那这时我们会选择用startAnimator2()的方式。(两种执行效果相同)
* */
startAnimator2();
break;
}
} private void startAnimator1() {
//透明动画
ObjectAnimator animator = ObjectAnimator.ofFloat(btn_click, "alpha", 0F, 1F);
animator.setDuration(1000);
//为动画设置监听
animator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) { } @Override
public void onAnimationEnd(Animator animation) {
/**
* 大部分情况下,我们都要监听的是这个,在动画结束后,执行什么操作
* 这里,我们只弹出一个Toast。
* */
Toast.makeText(MainActivity.this, "动画执行结束", Toast.LENGTH_SHORT).show();
} @Override
public void onAnimationCancel(Animator animation) { } @Override
public void onAnimationRepeat(Animator animation) { }
});
animator.start();
} private void startAnimator2() {
//透明动画
ObjectAnimator animator = ObjectAnimator.ofFloat(btn_click, "alpha", 0F, 1F);
animator.setDuration(1000);
//为动画设置监听
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
Toast.makeText(MainActivity.this, "动画执行结束", Toast.LENGTH_SHORT).show();
}
});
animator.start();
}
}