自定义ListView步骤
2016-06-04 本文已影响1240人
前端develop
1.为ListView的子项创建一个自定义布局,在Layout目录下新建一个xxx_item.xml文件;
2.创建一个实体类,作为ListView适配器的适配类型。
例如
public class Fruit {
private String name;
private int imageId;
public Fruit(String name, int imageId) {
this.name = name;
this.imageId = imageId;
}
//生成各属性的getter方法
public String getName() {
return name;
}
public int getImageId() {
return imageId;
}
}
3.创建一个自定义的适配器继承ArrayAdapter,并将泛型指定为第2步的实体类。
例如
public class FruitAdapter extends ArrayAdapter<Fruit> {
private int resourceId;
//构造函数传入context、item布局文件textViewResouId、数据对象objects
public FruitAdapter(Context context, int textViewResourceId, List<Fruit> objects) {
super(context, textViewResourceId, objects);
resourceId = textViewResourceId;
}
//复写getView将数据显示到布局上并将view返回
@Override
public View getView(int position,View convertView,ViewGroup parent){
Fruit fruit = getItem(position);//获取当前项的Fruit实例
View view =LayoutInflater.from(getContext()).inflate(resourceId,null);
ImageView fruitImage = (ImageView)view.findViewById(R.id.fruit_image);
TextView fruitName = (TextView)view.findViewById(R.id.fruit_name);
fruitImage.setImageResource(fruit.getImageId());
fruitName.setText(fruit.getName()); retrun view;
}
}
为了优化ListView,可以将第3步的代码修改成下面的例子
public class FruitAdapter extends ArrayAdapter {
……
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Fruit fruit = getItem(position);
View view;
ViewHolder viewHolder;
if (convertView == null) {
view=LayoutInflater.from(getContext()).inflate(resourceId,null);
viewHolder = new ViewHolder();
viewHolder.fruitImage = (ImageView) view.findViewById (R.id.fruit_image);
viewHolder.fruitName = (TextView) view.findViewById (R.id.fruit_name);
view.setTag(viewHolder); // 将ViewHolder存储在View中
} else {
view = convertView;
viewHolder = (ViewHolder) view.getTag(); // 重新获取ViewHolder
}
viewHolder.fruitImage.setImageResource(fruit.getImageId());
viewHolder.fruitName.setText(fruit.getName());
return view;
}
class ViewHolder {
ImageView fruitImage;
TextView fruitName;
}
}
4.在MainActivity为ListView设置Adapter
public class MainActivity extends Activity{
private List fruitList = new ArrayList();
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initFruits();//初始化水果数据将数据保存到fruitList,具体函数就不写了
//实例化Adapter
FruitAdapter adapter = new FruitAdapter(MainActivity.this,R.layout.fruit_item,fruitList);
ListView listView = (ListView) findViewById(R.id.list_view);
//为listView设置adapter
listView.setAdapter(adapter);
}
}