Adding animation to a ListView in order to expand/collapse content

六眼飞鱼酱① 提交于 2019-12-03 03:41:01
Udinic

To do that, I built an Animation class, which animates the margin to negative values, making the item disappear.

The animation looks like this:

public class ExpandAnimation extends Animation {
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
    super.applyTransformation(interpolatedTime, t);

    if (interpolatedTime < 1.0f) {

        // Calculating the new bottom margin, and setting it
        mViewLayoutParams.bottomMargin = mMarginStart
                + (int) ((mMarginEnd - mMarginStart) * interpolatedTime);

        // Invalidating the layout, making us seeing the changes we made
        mAnimatedView.requestLayout();
    }
}
}

I have an entire example app for this animation on my blog post

Tried Udinic's solution, but finally chose this alternative:

res/anim/scale_down.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<scale
    android:duration="700"
    android:fromXScale="1.0"
    android:fromYScale="1.0"
    android:pivotX="50%"
    android:pivotY="0%"
    android:toXScale="1.0"
    android:toYScale="0.0" />
</set>

Animate ListView implementation:

protected void animateView(final View v, final int animResId, final int endVisibility){
    Animation anim = AnimationUtils.loadAnimation(getApplicationContext(),
            animResId);
    anim.setAnimationListener(new Animation.AnimationListener() {
        public void onAnimationStart(Animation animation) {
            v.setVisibility(View.VISIBLE);
        }
        public void onAnimationEnd(Animation animation) {
            v.setVisibility(endVisibility);
        }
        public void onAnimationRepeat(Animation animation) {}
    });
    v.startAnimation(anim);
}

Example calls to animate my ListView (or any View child class):

animateView(listView1, R.anim.scale_down, View.GONE);
animateView(listView1, R.anim.scale_up, View.VISIBLE);

It is working on my KitKat phone.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!