Search code examples
androidandroid-linearlayoutandroid-cursoradapter

Dynamic list of items from Cursor into LinearLayout, without using a ListView


I'd like to display a few (5-ish) items from a Cursor in a list, and I'd like to keep it in sync with the content of the cursor (which in turn points to a database), but I don't want to use ListViews. Instead, I'd like to populate a plain old LinearLayout.

I seem to understand that I need to create a custom CursorAdapter and override the newView() and bindView() methods. What I don't understand is who is responsible for iterating over the cursor's items (does the CursorAdapter do it? Should my code do it?), how do the views for each item get parented to the LinearLayout and who is responsible for creating new views for new items in the cursor or removing views for items that are no longer available through the cursor?

Somehow I have a hunch that the CursorAdapter does already most of the work, but I can't quite put together all the pieces of the puzzle. Do I just inflate a row layout in newView() and add it to the LinearLayout directly? And how does a row gets removed if the cursor no longer has the associated data?

Thanks for your help!

Manu


Solution

  • Well, I would do the following:

    • Create a custom class, a subclass of LinearLayout, just to make it simple. Let's call it MyList
    • You pass the CursorAdapter instance to this class (eg. create a setAdapter method)
    • When receiving the adapter, MyList will register for data changes (CursorAdapter.registerDataSetObserver). When the data set changes, call a method "populate"
    • When receiving the adapter, also call "populate" directly, to get the initial contents
    • Implement MyList.populate: ** call removeAllViews ** for each item (iterate through the cursor) call addView(CursorAdapter.newView(getContext(), cursor, this))

    That's it in short. Of course later on you might want to optimize it, and keep the old views and use CursorAdapter.bindView instead, so you wouldn't need to create new heavy java objects.