【发布时间】:2014-03-21 21:52:35
【问题描述】:
我正在尝试实现自定义类型的 ListAdapter。底层数据可以来自数据库或其他类型的数据源,这意味着我应该扩展 BaseAdapter。但是,我也想使用 SimpleCursorAdapter 和 SimpleAdapter 中实现的现有逻辑。
我想一种说法是我想在 BaseAdapter 和它的后代之间“注入”一个新类......
基本上我想要实现的就是这个图,只是为了说明问题。
下面是我想出的一种可能的解决方案,但我很好奇做这种事情的标准方法是什么?
public class ExpandableAdapterHelper{
public void onNewView(View view, long id) {
// Do stuff
}
public void onBindView(View view, long id) {
// Do stuff
}
}
public class ExpandableCursorAdapter extends SimpleCursorAdapter{
private ExpandableAdapterHelper expandableAdapterHelper;
public ExpandableCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
super( context, layout, c, from, to, flags );
expandableAdapterHelper = new ExpandableAdapterHelper();
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View newItem = super.newView(context, cursor, parent);
expandableAdapterHelper.onNewView(newItem, cursor.getInt(0));
return newItem;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
super.bindView(view, context, cursor);
expandableAdapterHelper.onBindView(view, cursor.getInt(0));
}
}
public class ExpandableSimpleAdapter extends SimpleAdapter{
private ExpandableAdapterHelper expandableAdapterHelper;
public ExpandableSimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to){
super( context, data, resource, from, to );
expandableAdapterHelper = new ExpandableAdapterHelper();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if( convertView == null ){
expandableAdapterHelper.onNewView(convertView, getItemId(position));
}
else{
expandableAdapterHelper.onBindView(convertView, getItemId(position));
}
return convertView;
}
}
【问题讨论】:
-
使用
SimpleCursorAdapter。默认情况下它将处理Cursor,如果您有任何其他类型的数据而不是将其转换为MatrixCursor(应该相当简单)然后将其传递给适配器。这可能是最简单的解决方案。 -
谢谢!我不知道 MatrixCursor,但这绝对是要走的路。特别是因为我现有的解决方案是基于 SimpleCursorAdapter 的(以一种骇人听闻的方式 - 我使用 SQLite 数据库作为数据和我的适配器之间的一种代理......非常丑陋:) 这应该使它更有效率和干净!
标签: android inheritance multiple-inheritance listadapter