views:

60

answers:

1

What I'm trying to do is to show some data for a book like Title, Author, and a Cover, and beneath these data, to have a ListView containing a list of clickable chapters.

One way I've thought would be to have a ListView with different type of cells, where the first would contain the data, and the rest of them would be simple cells containing the chapters. The ListView binds to a custom CursorAdapter that implements the newView(...) and bindView(...) methods, which I don't know how to customise in order to return different types of cells based on the cell's position.

@Override
public void bindView(View view, Context context, Cursor cursor) {

    TextView title = (TextView) view.findViewById(R.id.title);
    title.setText(cursor.getString(cursor.getColumnIndex(Constants.TITLE)));
    ..
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    LayoutInflater inflater = LayoutInflater.from(context);
    View v = inflater.inflate(R.layout.bookcell, parent, false);
    bindView(v, context, cursor);
    return v;
}

How should I do that?

Thanks!

+1  A: 

You can do this by:

  1. Overriding getViewTypeCount() and returning the number of distinct row layouts
  2. Overriding getItemViewType() and returning a 0-based index of the row layout to be used for a given position
  3. Adjusting newView() and bindView() to use the right row type based on the position (e.g., newView() inflates different row layouts based on position)

Or, you can try assembling your adapter from pieces, using something like my MergeAdapter.

CommonsWare
How should I adjust the newView and bindView? They don't get a position argument... Could you provide a code sample? Thanks!
georgeb89
@georgeb89: Your position can be found by calling `getPosition()` on your `Cursor`.
CommonsWare
Hmm.. I tried to do that, but now I realize that the data come from two different datasets (one for the Chapters and one for the rest of the book details), so I would need 2 different Cursors... :S
georgeb89
@georgeb89: A join might work, if you are querying SQLite. Otherwise, yes, you will need your own rather sophisticated adapter to blend the two cursors into the header-and-detail model you're seeking.
CommonsWare
Could I use your own MergeAdapter to solve the issue? I'm querying SQLite but I wouldn't like to use a join...
georgeb89
@georgeb89: `MergeAdapter` isn't quite set up for your scenario. In your case, you have a single `CursorAdapter` (all chapters) which you want split up into segments with interspersed headers. `MergeAdapter` is designed for a bunch of smaller `CursorAdapters` (one per book) and interspersed headers.
CommonsWare