iFoukis
iFoukis

Reputation: 274

Expand listview with animation (on few items - not the whole list)

I have a List with 6 items (strings) and the last item has the string "more options".

After clicking on "more options", the list should add 3 items between item5 and "more options" (last item). For example:

 - item1
 - item2
 - item3
 - item4
 - item5
 - "more options"

I use notifyDataSetChanged() to notify the Adapter that new items have been added to the list.

What's the best way to animate the expansion of the list from 6 items to 9 items without recreating the whole list?

Final look of the list (after adding item6, item7, and item8 with an animation):

 - item1
 - item2
 - item3
 - item4
 - item5
 - item6 (new)
 - item7 (new)
 - item8 (new)
 - "more options"

Is it bad practice/hacky to put outset every item needed and make item6, item7, item8 invisible? Whats the best way?

Upvotes: 0

Views: 279

Answers (1)

keshav
keshav

Reputation: 3255

you have to create animation something like this

 private void enlarge(final View v, AnimationListener al)
{
    final int initialHeight = v.getMeasuredHeight();

    Animation anim = new Animation() {
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t)
        {
            if (interpolatedTime == 1)
            {
                v.setVisibility(View.GONE);
            }
            else
            {
                v.getLayoutParams().height = initialHeight + (int) (initialHeight * interpolatedTime);
                v.requestLayout();
            }
        }

        @Override
        public boolean willChangeBounds()
        {
            return true;
        }
    };

    if (al != null)
    {
        anim.setAnimationListener(al);
    }
    anim.setDuration(ANIMATION_DURATION);
    v.startAnimation(anim);
}

then use this when adding items to the listview before that create AnimationListener

  AnimationListener al = new AnimationListener() {
        @Override
        public void onAnimationEnd(Animation arg0)
        {
            mAnimList.remove(index);

            ViewHolder vh = (ViewHolder) v.getTag();
            vh.needInflate = true;

            mMyAnimListAdapter.notifyDataSetChanged();
        }

        @Override
        public void onAnimationRepeat(Animation animation)
        {
        }

        @Override
        public void onAnimationStart(Animation animation)
        {
        }
    };

and finaly call

  enlarge(v, al);

Upvotes: 1

Related Questions