How to animate individual elements in ListView

2019-04-15 03:12发布

I'm doing a small Android app based around a ListView. When the user selects one or more elements in the list and subsequently selects a menu item from the ActionBar I would like to do a small animation on the selected elements in the list, and this is where things go wrong.

Nothing animates - nor does anything fail. The following code piece is a simplified version of what I'm doing:

private void animateListViewItem()
{
    TranslateAnimation anim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,Animation.RELATIVE_TO_SELF, 0.0f,
            Animation.RELATIVE_TO_SELF, -1.0f,Animation.RELATIVE_TO_SELF, 0.0f);
    anim.setDuration(2000);
    View v = fragment.getListAdapter().getView(fragment.getListView().getFirstVisiblePosition(), null, null);
    v.startAnimation(anim);
}

When I messed around with it, trying to figure out what was wrong, I at one point substituted the item with the entire ListView to rule out the animation as the source of the problem - like this.

private void animateListViewItem()
{
    TranslateAnimation anim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,Animation.RELATIVE_TO_SELF, 0.0f,
            Animation.RELATIVE_TO_SELF, -1.0f,Animation.RELATIVE_TO_SELF, 0.0f);
    anim.setDuration(2000);
    fragment.getListView().startAnimation(anim);
}

To my amazement, that worked perfect!

So my question is - why can't I animate the individual elements in a ListView? Or is there something I am doing wrong?

Thanks!

P.S. For the record the ListView is populated with custom views (LinearLayouts), and I have checked that I get the right item before animating.

1条回答
贼婆χ
2楼-- · 2019-04-15 04:03

I found out what the issue was:

View v = fragment.getListAdapter().getView(fragment.getListView().getFirstVisiblePosition(), null, null);

This line was the problem. It returns a new View to display the underlying data at the specified position in the list not the existing View. So the returned View has nothing to do with the list.

Instead doing this:

View v = fragment.getListView().getChildAt(fragment.getListView().getFirstVisiblePosition());

Got me the View that the list was using and the animation worked as expected.

查看更多
登录 后发表回答