自定义ObjectAnimator属性实现
package com.loaderman.customviewdemo; import android.animation.ObjectAnimator; import android.graphics.Point; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; public class MainActivity extends AppCompatActivity { private FallingBallImageView ball_img; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // ball_img = (FallingBallImageView) findViewById(R.id.ball_img); findViewById(R.id.start_anim).setOnClickListener(new View.OnClickListener() { public void onClick(View v) { ObjectAnimator animator = ObjectAnimator.ofObject(ball_img, "fallingPos", new FallingBallEvaluator(), new Point(0, 0), new Point(500, 500));//set函数对于的属于应该是fallingPos或者FallingPos animator.setDuration(2000); animator.start(); } }); } }
package com.loaderman.customviewdemo; import android.animation.TypeEvaluator; import android.graphics.Point; public class FallingBallEvaluator implements TypeEvaluator<Point> { private Point point = new Point(); public Point evaluate(float fraction, Point startValue, Point endValue) { point.x = (int)(startValue.x + fraction *(endValue.x - startValue.x)); if (fraction*2<=1){ point.y = (int)(startValue.y + fraction*2*(endValue.y - startValue.y)); }else { point.y = endValue.y; } return point; } }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_gravity="center" tools:context="com.loaderman.customviewdemo.MainActivity"> <com.loaderman.customviewdemo.FallingBallImageView android:id="@+id/ball_img" android:layout_width="50dp" android:layout_height="50dp" android:src="@drawable/cicle"/> <Button android:id="@+id/start_anim" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="开始动画"/> </LinearLayout>
package com.loaderman.customviewdemo;
import android.content.Context;
import android.graphics.Point;
import android.util.AttributeSet;
public class FallingBallImageView extends android.support.v7.widget.AppCompatImageView {
public FallingBallImageView(Context context) {
super(context);
}
public FallingBallImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FallingBallImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setFallingPos(Point pos){
layout(pos.x, pos.y, pos.x + getWidth(), pos.y + getHeight());
}
}
最后,关注【码上加油站】微信公众号后,有疑惑有问题想加油的小伙伴可以码上加入社群,让我们一起码上加油吧!!!