问题
继承ArrayAdapter构造自己类时候,我是这样写的
public class IconAdapter extends ArrayAdapter<Icon> {
private List<Icon> images;
private int resourceId;
private Context context;
public IconAdapter(Context context, int resource, List<Icon> images) {
super(context, resource, images);
this.context = context;
this.resourceId = resourceId;
this.images = images;
}
发现网上有些代码只是这样
public IconAdapter(Context context, int resource, List<Icon> images) {
super(context, resource, images);
this.resourceId = resourceId;
}
我疑惑, 不需要一个 List 来保存数据吗?
查看ArrayAdapter源代码
为了突出重点, 下面只列出我们需要的源代码
public class ArrayAdapter<T> extends BaseAdapter implements Filterable, ThemedSpinnerAdapter {
private List<T> mObjects;
public ArrayAdapter(Context context, @LayoutRes int resource, @IdRes int textViewResourceId,
@NonNull List<T> objects) {
mContext = context;
mInflater = LayoutInflater.from(context);
mResource = mDropDownResource = resource;
mObjects = objects;
mFieldId = textViewResourceId;
}
注意到ArrayAdapter其实源代码自带了 mObjects 集合变量
如何获取集合里的某个元素
本来我是这样做的
Icon icon = images.get(position);
后来发现源代码里有 getItem 方法
public T getItem(int position) {
return mObjects.get(position);
}
获取 context
我本来是打算定义一个变量 context, 在构造函数里面初始化
private Context context;
public IconAdapter(Context context, int resource, List<Icon> images, int resourceId) {
super(context, resource, images);
this.context = context;
this.resourceId = resourceId;
this.images = images;
}
然后其他方法使用这个变量就行,
LayoutInflater.from(context).inflate(resourceId, parent)
发现也是多虑了, 源代码已经实现了
public Context getContext() {
return mContext;
}
附上最终的public class IconAdapter extends ArrayAdapter<Icon>
源代码
package com.example.tomchen.testlistview;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
/**
* Created by tomchen on 9/1/15.
*/
public class IconAdapter extends ArrayAdapter<Icon> {
private int resourceId;
public IconAdapter(Context context, int resource, List<Icon> icons) {
super(context, resource, icons);
this.resourceId = resource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Icon icon = getItem(position);
View view;
if (convertView == null) {
view = LayoutInflater.from(getContext()).inflate(resourceId, null);
} else {
view = convertView;
}
ImageView image = (ImageView) view.findViewById(R.id.icon);
image.setImageResource(icon.getImageId());
TextView text = (TextView) view.findViewById(R.id.text);
text.setText(icon.getName());
return view;
}
}