Search code examples
javaandroidandroid-layoutandroid-animationdocument-layout-analysis

How to set start offset for a (recyclerview) layout animation?


Using this post, one can set layout animation for recyclerview as follow:

res/anim/layout_animation.xml

<?xml version="1.0" encoding="utf-8"?>
    <layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
        android:animation="@anim/item_animation_fall_down"
        android:animationOrder="normal"
        android:delay="15%" />

This works very well. But the fragment that My recyclerview live there has a slide windows transition from left to right and the recyclerview layout animation starts when that fragment transition is in its middle.

So I want to set a delay for recyclerview layout animation to force it starts exactly after the end of fragment slide transition.

How to set start offset for a layout animation? (preferred solution)

I think this can be done by adding a listener to the fragment's windows animation, if so how?

This is my fragment transition

<?xml version="1.0" encoding="utf-8"?>

<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="@android:integer/config_longAnimTime"
    android:interpolator="@android:interpolator/fast_out_slow_in">
    <translate
        android:fromXDelta="100%"
        android:toXDelta="0%"
        android:fromYDelta="0%"
        android:toYDelta="0%"/>
</set>

and this is the fragment:

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // data to populate the RecyclerView with
    ArrayList<String> animalNames = new ArrayList<>();
    animalNames.add("Horse");
    animalNames.add("Cow");
    animalNames.add("Camel");
    animalNames.add("Sheep");
    animalNames.add("Goat");

    // set up the RecyclerView
    RecyclerView recyclerView = findViewById(R.id.rvAnimals);
    adapter = new MyRecyclerViewAdapter(this, animalNames);
    adapter.setClickListener(this);
    recyclerView.setAdapter(adapter);
}

Solution

  • You can use handler for animation if you want to delay

    Handler().postDelayed({
        // Start RecyclerView layout animation
        val controller = AnimationUtils.loadLayoutAnimation(context, R.anim.layout_animation)
        recyclerView.layoutAnimation = controller
        recyclerView.scheduleLayoutAnimation()
    }, resources.getInteger(android.R.integer.config_shortAnimTime).toLong())