您使用的适配器类型应取决于您尝试呈现的数据类型。理想情况下,适配器是一个非常薄的对象,它将数据集中的项目绑定到视图。 ArrayAdapter 为小型有界数据集提供此功能,CursorAdapter 为 SQLite 查询生成的数据集提供此功能。
并非所有数据集都适合 Android 框架中提供的 Adapter 类所呈现的模型,但编写自己的数据集很容易。呈现所有正整数的列表是一个很好的例子,因为它根本不需要涉及与底层数据模型的通信。虽然维护大型数据集的滑动窗口对于某些数据来说可能是一种有用的方法,但这里不需要它。
从...开始BaseAdapter
:
public class IntRangeAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private int mItemResource;
public IntRangeAdapter(Context context, int itemLayout) {
// We'll use this to generate new item layouts
mInflater = LayoutInflater.from(context);
// This is the layout resource we'll use for each item
mItemResource = itemLayout;
}
public int getCount() {
// Since this adapter presents all positive integers,
// we have Integer.MAX_VALUE items.
return Integer.MAX_VALUE;
}
public Object getItem(int position) {
// Each item is simply its position index.
return position;
}
public long getItemId(int position) {
// Our items won't change and we don't need stable IDs,
// so the position of an item is also its ID.
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
// Inflate a new item layout if we weren't given an existing
// one to reuse via the convertView parameter.
convertView = mInflater.inflate(mItemResource, parent, false);
}
// Find the TextView where we will label the item.
// (This can be optimized a bit for more complex layouts
// but we won't bother for this example.)
TextView tv = (TextView) convertView.findViewById(android.R.id.text1);
// Set the item text based on its position.
tv.setText("Item " + position);
return convertView;
}
}
从您发布的活动代码中使用它只需更改您的setAdapter
调用并删除循环来设置数据:
this.setListAdapter(new IntRangeAdapter(this,
android.R.layout.simple_list_item_1));
如果您想了解有关使用 ListViews 的更多信息,Google I/O 2010 的演讲给出了不错的介绍:http://www.youtube.com/watch?v=wDBM6wVEO70 http://www.youtube.com/watch?v=wDBM6wVEO70