Creating a custom CursorAdapter for ListView ...

来源:百度文库 编辑:神马文学网 时间:2024/04/29 17:03:30

When populate data from database to a ListView, sometimes you want to do more than just map database column values to list row. At this situation, SimpleCursorAdapter is not suitable . Your need to create a custom CursorAdapter. The steps are simple:

  1. Subclass CursorAdapter
  2. Override bindView and newView

Code

row.xml
 
view raw gistfile1.xsl This Gist brought to you by GitHub.
RowAdapter.java
class RowAdapter extends CursorAdapter { private final LayoutInflater mInflater; public RowAdapter(Context context, Cursor c, boolean autoRequery) {super(context, c, autoRequery);mInflater = LayoutInflater.from(context);} public RowAdapter(Context context, Cursor c) {super(context, c);mInflater = LayoutInflater.from(context);} @Overridepublic void bindView(View view, Context context, Cursor cursor) {TextView tvDate = (TextView) view.findViewById(R.id.tv_date);TextView tvTime = (TextView) view.findViewById(R.id.tv_time);TextView tvWeek = (TextView) view.findViewById(R.id.tv_week);TextView tvVs = (TextView) view.findViewById(R.id.tv_vs); StringBuilder date = new StringBuilder(cursor.getString(cursor.getColumnIndex(DatabaseHelper.C_DATE)));StringBuilder time = new StringBuilder(cursor.getString(cursor.getColumnIndex(DatabaseHelper.C_TIME)));String week = cursor.getString(cursor.getColumnIndex(DatabaseHelper.C_WEEK));String vs = cursor.getString(cursor.getColumnIndex(DatabaseHelper.C_VS)); if (DateFormat.format("yyyyMMdd", System.currentTimeMillis()).toString().equals(date.toString())) {view.setBackgroundColor(Color.BLUE);} tvDate.setText(date.insert(4, '-').insert(7, '-'));tvTime.setText(time.insert(time.length() - 2, ':'));tvWeek.setText(week);tvVs.setText(vs);} @Overridepublic View newView(Context context, Cursor cursor, ViewGroup parent) {final View view = mInflater.inflate(R.layout.list_item, parent, false);return view;}}