Question

Where is the source code that manages View re-use in Android? I can think of three distinct parts to this process, but there may be more:

  1. The logic that determines if a View is eligible for re-use
  2. The code that manages pools of Views that can be re-used
  3. The code that removes a re-usable View from the pool and resets its property values to represent a logically different View

EDIT: The blog post Developing applications for Android – gotchas and quirks gives the following example:

public class PencilWise extends ListActivity {
    View activeElement;
    // ...
    @Override
    public void onCreate ( Bundle savedInstanceState ) {
        // ...
        this.getListView( ).setOnItemClickListener ( new OnItemClickListener ( ) {
            public void onItemClick ( AdapterView<?> parent, View view, int position, long id ) {
                MyActivity.this.activeElement = view;
                MyActivity.this.showDialog ( DIALOG_ANSWER );
            }
        } );
    }
}

The showDialog method will display the answer dialog, which needs to know what question the user has opened. The problem is that by the time the dialog opens, the view passed to onItemClick might have been reused, and so activeElement would no longer point to the element the user clicked to open the dialog in the first place!

Was it helpful?

Solution

I think a good example of what you're looking for is in the AbsListView.RecycleBin inner class located in the widget package.
You can see the code online here: https://android.googlesource.com/platform/frameworks/base/+/android-2.2_r1.1/core/java/android/widget/AbsListView.java#3888

Here's an excerpt from the documentation:

The RecycleBin facilitates reuse of views across layouts. The RecycleBin has two levels of storage: ActiveViews and ScrapViews. ActiveViews are those views which were onscreen at the start of a layout. By construction, they are displaying current information. At the end of layout, all views in ActiveViews are demoted to ScrapViews. ScrapViews are old views that could potentially be used by the adapter to avoid allocating views unnecessarily.

OTHER TIPS

Views recycling is performed by AbsListView and their subclasses ListView and GridView. You can find the source code of these classes here: https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/widget

Start with ListView and AbsListView.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top