我认为这是最好的方法。使用通用的ArrayAdapter类并扩展自己的对象适配器非常简单,如下所示:
public abstract class GenericArrayAdapter<T> extends ArrayAdapter<T> {
// Vars
private LayoutInflater mInflater;
public GenericArrayAdapter(Context context, ArrayList<T> objects) {
super(context, 0, objects);
init(context);
}
// Headers
public abstract void drawText(TextView textView, T object);
private void init(Context context) {
this.mInflater = LayoutInflater.from(context);
}
@Override public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder vh;
if (convertView == null) {
convertView = mInflater.inflate(android.R.layout.simple_list_item_1, parent, false);
vh = new ViewHolder(convertView);
convertView.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
drawText(vh.textView, getItem(position));
return convertView;
}
static class ViewHolder {
TextView textView;
private ViewHolder(View rootView) {
textView = (TextView) rootView.findViewById(android.R.id.text1);
}
}
}
这是您的适配器(示例):
public class SizeArrayAdapter extends GenericArrayAdapter<Size> {
public SizeArrayAdapter(Context context, ArrayList<Size> objects) {
super(context, objects);
}
@Override public void drawText(TextView textView, Size object) {
textView.setText(object.getName());
}
}
最后,如何初始化它:
ArrayList<Size> sizes = getArguments().getParcelableArrayList(Constants.ARG_PRODUCT_SIZES);
SizeArrayAdapter sizeArrayAdapter = new SizeArrayAdapter(getActivity(), sizes);
listView.setAdapter(sizeArrayAdapter);
我用TextView布局重力自定义ArrayAdapter创建了一个Gist:
https://gist.github.com/m3n0R/8822803