这篇文章用来讲解RecyclerView自定义进入动画
分为三个步骤
1.自定义RecyclerView2.xml中定义布局动画
3.界面打开后执行进入动画
1.自定义RecyclerView
public class CustomRecyclerView extends RecyclerView {
public CustomRecyclerView(Context context) {
super(context);
}
public CustomRecyclerView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public CustomRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void setLayoutManager(LayoutManager layout) {
if (layout instanceof LinearLayoutManager) {
super.setLayoutManager(layout);
}else {
throw new ClassCastException("请使用LinearLayoutManager");
}
}
@Override
protected void attachLayoutAnimationParameters(View child, ViewGroup.LayoutParams params, int index, int count) {
if (getAdapter() != null && getLayoutManager() instanceof LinearLayoutManager){
LayoutAnimationController.AnimationParameters animationParameters = ( LayoutAnimationController.AnimationParameters)params.layoutAnimationParameters;
if (animationParameters == null){
AlphaAnimation alphaAnimation = new AlphaAnimation(0,1);
alphaAnimation.setDuration(1000);
animationParameters = new LayoutAnimationController.AnimationParameters();
params.layoutAnimationParameters = animationParameters;
}
animationParameters.count = count;
animationParameters.index = index;
}else {
super.attachLayoutAnimationParameters(child, params, index, count);
}
}
}
2.xml中定义布局动画
定义布局动画的xml文件
recycler_animation.xml
Android:delay=”15%”表示延迟时间的百分数,一个一个的动画
android:animationOrder=”normal”表示进入的动画顺序,normal:按顺序,reverse:反向顺序 ,random:随机顺序
<?xml version="1.0" encoding="utf-8"?>
<layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
android:animation="@anim/slide_in_bottom"
android:delay="15%"
android:animationOrder="normal"
/>
slide_in_bottom.xml
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/decelerate_interpolator"
android:fromYDelta="100%p" android:toYDelta="0"
android:duration="@android:integer/config_mediumAnimTime"/>
3.界面打开后执行进入动画
我们想在Activity完全打开后执行动画,android5.0以后可以监听到这个完成的动作
@Override//activity进入动画完成时,调用设置recyclerview的进入动画
public void onEnterAnimationComplete() {
super.onEnterAnimationComplete();
mAdapter = new MyAdapter();
mRecycler.setAdapter(mAdapter);
mRecycler.scheduleLayoutAnimation();//安排动画
}