我们经常使用ArrayAdapter对简单的数据进行填充,从常用的构造方法
public ArrayAdapter(Context context, int resource, T[] objects) {
init(context, resource, 0, Arrays.asList(objects));
}
public ArrayAdapter(Context context, int resource, List<T> objects) {
init(context, resource, 0, objects);
}
可以看出我们只需要传一个简单的数组和一个资源文件即可,这个资源文件常常只有一个元素就是textview
今天我们有了一个新的需求,需要让listview的item显示的稍微复杂点.虽然这个需求还是 很简单,很容易实现的,但是最为比较懒的我来说这是不能满足我的需要的.
我当时就想ArrayAdapter不会就这么简单的能显示单个textview吧 ?如果这是这样谷歌的工程师也太low了吧.事实证明谷歌是一个伟大的公司,他们的工程师也是.
谷歌的工程师早就想替我们想考虑了很多情况,当然我现在的需求也是不在话下.只是显示一下复杂的界面,要填充的还是那个textview.那么问题来了.arrayadapter
是怎么在复杂的item中找到那个需要填充数据的textview呢? 于是我去看了源码,果然ArrayAdapter还提供了另外两个构造方法
public ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects) {
init(context, resource, textViewResourceId, Arrays.asList(objects));
}
public ArrayAdapter(Context context, int resource, int textViewResourceId, List<T> objects) {
init(context, resource, textViewResourceId, objects);
}
这两个构造方法中有两个资源id,想必一看名字就知道是怎么用的了.
下面在看一下谷歌的工程师是怎么实现的
private void init(Context context, int resource, int textViewResourceId, List<T> objects) {
mContext = context;
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mResource = mDropDownResource = resource;
mObjects = objects;
mFieldId = textViewResourceId;
}
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
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;
}
看到这里应该是明白了许多....哈哈