I’ve been writing a bit more Android code, and came upon the need to write a custom CursorAdapter for a ListView, as the way I wanted to display data from a Cursor was dependent on relationships between different fields of the database.
Of the problems I encountered, the most obvious was when I tried to inflate views using View.inflate(), and found I would get the following error:
UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView at android.widget.AdapterView |
After a bit of rummaging around, I found that the following bit of code would work when attached to a ListView using setAdapter().
public class ExampleCursorAdapter extends CursorAdapter { public ExampleCursorAdapter(Context context, Cursor c) { super(context, c); } @Override public void bindView(View view, Context context, Cursor cursor) { TextView summary = (TextView)view.findViewById(R.id.summary); summary.setText(cursor.getString( cursor.getColumnIndex(ExampleDB.KEY_EXAMPLE_SUMMARY))); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { LayoutInflater inflater = LayoutInflater.from(context); View v = inflater.inflate(R.layout.item, parent, false); bindView(v, context, cursor); return v; } } |
The above example code doesn’t actually require a CursorAdapter, it would easily be implemented using a SimpleCursorAdapter, but it serves to show the idea. Basicly, get a LayoutInflater from the context, and use the version of inflate() that does not attach to the root view.