ListView: Prevent a view from recycling

2019-03-20 21:12发布

问题:

I have a ListView wich use recycled views. I'm trying to prevent a view from recycle. So I use setHasTransientState:

android.support.v4.view.ViewCompatJB.setHasTransientState(View view, boolean hasTransientState)

It works very well on Jellybean version but it doesn't do anything on Api < 16. Is there a way to make it work or there is different approach for pre Jellybean ?


I found out how to set a RecyclerListener like @Daniel Chow suggested.

listView.setRecyclerListener(new RecyclerListener() {
        @Override
        public void onMovedToScrapHeap(View view) {
            // Stop animation on this view
        }
});

回答1:

For pre Jellybean, I think you can just use setRecyclerListener on ListView and when RecyclerListener#onMovedToScrapHeap(View view) is called, clear the animation on the view who has been recycled and directly do the final job which was supposed to be done when animation ends.

The code inside onMovedToScrapHeap(View view) depends on how you implement the animation, e.g. you can call View#clearAnimation() if you previously used View#startAnimation to start animation.



回答2:

Use android.support.v4.view.ViewCompat.setHasTransientState(View view, boolean hasTransientState) instead of android.support.v4.view.ViewCompatJB.setHasTransientState(View view, boolean hasTransientState)



回答3:

Besides the animation problem Daniel talked about, another issue where knowing when your view is recycled has to do with memory management. If you are putting large, memory intensive bitmaps in your list items, it may be possible that you don't want your view recycled if its not likely to be re-used by other items. This hook gives you a chance to clear the bitmap you may have assigned to an ImageView. Hopefully, this is a rare problem.