先上效果图:
实现原理:
通过自定义一个布局,继承自LinearLayout,然后在这个布局当中添加5条竖线,也即是5个矩形View;通过对这5个View分别加入属性动画,即可实现。动画是一个组合动画:纵向向后旋转以及纵向的伸缩。
具体代码:
/**
* 仿英雄联盟波形加载动画
* @author yangmbin
* created at 2016/11/25 17:17
*/
public class LoadingView extends LinearLayout {
public LoadingView(Context context, AttributeSet attrs) {
super(context, attrs);
// 添加5条竖状矩形(波形)
for (int i = 0; i < 5; i++) {
final View v = new View(context);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(dip2px(7), dip2px(20));
params.leftMargin = dip2px(2f);
v.setBackgroundColor(Color.parseColor("#cccccc"));
v.setLayoutParams(params);
addView(v);
// 纵向旋转
ObjectAnimator oaRotation = ObjectAnimator.ofFloat(v, "rotationX", 0f, 360f);
oaRotation.setRepeatCount(ObjectAnimator.INFINITE);
oaRotation.setRepeatMode(ObjectAnimator.RESTART);
oaRotation.setInterpolator(new LinearInterpolator()); // 避免循环一次就停顿一下的问题
oaRotation.setStartDelay(100 * i);
// 纵向伸缩
ObjectAnimator oaScale = ObjectAnimator.ofFloat(v, "scaleY", 1.5f, 1.5f, 1.5f);
oaScale.setRepeatCount(ObjectAnimator.INFINITE);
oaScale.setRepeatMode(ObjectAnimator.RESTART);
oaScale.setStartDelay(100 * i);
// 组合动画
AnimatorSet animSet = new AnimatorSet();
animSet.play(oaRotation).with(oaScale);
animSet.setDuration(2500);
animSet.start();
}
}
public int dip2px(float dpValue) {
final float scale = getContext().getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
}
使用方法也很简单,在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:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.demo.MainActivity">
<com.demo.LoadingView
android:layout_width="wrap_content"
android:layout_height="50dp"
android:orientation="horizontal"
android:layout_centerInParent="true"
android:gravity="center"/>
</RelativeLayout>
纵向的伸缩效果可以去掉,在上面的代码中没做任何的处理,可以自行修改达到自己想要的效果。