Search code examples
androidlistviewanimationoffset

Android ListView items animation - Animate only first visible items


I'm trying to reproduce this ListView items:

http://material-design.storage.googleapis.com/videos/components-progressandactivity-progressandactivity-2-drive.mobile-load.folders_large_xhdpi.webm

I've successfuly achieved it with these lines of code (not counting animation xml file):

//Set animation
    if(position > lastAnimPosition){
        lastAnimPosition = position;

        Animation anim = AnimationUtils.loadAnimation(context, R.anim.item_slide_in);
        anim.setStartOffset(50 * position);
        row.startAnimation(anim);
    }

So animations are fine, but when I scroll down, there's problem with offset - it's just huge and it gives feel like the app is loading item for too long. What I need to do, is find out when I should disable offset - or how to enable offset only for first showed items.


Solution

  • Use the layout animation attribute in your xml

    Docs here : http://developer.android.com/reference/android/view/ViewGroup.html#attr_android:layoutAnimation

    add a file to your res/anim folder of layout_item_slide_in.xml that has a reference to @anim/item_slide_in

    <?xml version="1.0" encoding="utf-8"?>
    <layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
            android:delay="0.5"
            android:animation="@anim/item_slide_in" />
    

    Now, change your listview xml slightty to include the android:layoutAnimation attribute and value

    <ListView
        android:id="@+id/foo"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layoutAnimation="@anim/layout_item_slide_in"" />
    

    this will achieve the same first load animation style you want w/o having to do it in code