本文源码下载:
具体下载目录在 /2013年资料/8月/16日/ListView_v2_系统提供的一些 adapter适配器
首先这个ArrayAdapter已经实现了BaseAdapter中的那四个override方法,并且这个适配器中只能有一个TextView组件,大家可能会问为什么,我们先看看ArrayAdapter的源代码
public View getView(int position, View convertView, ViewGroup parent) {
return createViewFromResource(position, convertView, parent, mResource);
}
private View createViewFromResource(int position, View convertView, ViewGroup parent,
int resource) {
View view;
TextView text;
if (convertView == null) {
view = mInflater.inflate(resource, parent, false);
} else {
view = convertView;
}
try {
if (mFieldId == 0) {
// If no custom field is assigned, assume the whole resource is a TextView
//arrayadatper直接将view强转为TextView
text = (TextView) view;
} else {
// Otherwise, find the TextView field within the layout
text = (TextView) view.findViewById(mFieldId);
}
} catch (ClassCastException e) {
Log.e("ArrayAdapter", "You must supply a resource ID for a TextView");
throw new IllegalStateException(
"ArrayAdapter requires the resource ID to be a TextView", e);
}
T item = getItem(position);
if (item instanceof CharSequence) {
text.setText((CharSequence)item);
} else {
text.setText(item.toString());
}
return view;
}
在main布局里面 加入listview 这个跟前面的一样
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
第二步:让MainActivity继承ListActivity,ListActivity中就有一个ListView,这样就可以直接使用setListAdapter(adapter)方法加入适配器就可以了
看一下源代码:
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//这里不能有这个了,因为ListActivity中已经有布局了,如果非得用自己的布局,也可以这个后面再说啦~~~
//setContentView(R.layout.activity_main);
//首先创建一个 ArrayAdapter
ArrayAdapter adapter = new ArrayAdapter(this,
R.layout.list_item, mStrings);
/*参数说明:
* context: 要放入当前activity的对象,也就是那个this.
* textViewResourceId: 这个要放入一个TextView的资源id,就是 R.layout.list_item
* objects: listView的行内容,也就是mStrings.
**/
//ListActivity中存在一个ListView,直接设置就好
setListAdapter(adapter);
}
private String[] mStrings = {//listview的一些行内容
"Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondanc