在ListView详解(一)中介绍了ListView的基本用法,重点是适配器的使用,通过适配器将要显示的数据传递给ListView中。上一个实例中只是使用最基本的ArrayAdapter,只能显示文字。下面我们将使用自定义适配器使得ListView的每个子项显示为图片与文字的组合。
ListView下的每一个子项均为一个对象实例,所以我们需要定义一个实体类作为适配器的适配类型。定义一个类Fruit:
Fruit.java
public class Fruit {
private String name;
private int imageId;
public Fruit(String name,int imageId){
this.name = name;
this.imageId = imageId;
}
public void setName(String name){
this.name = name;
}
public void setImageId(int imageId){
this.imageId = imageId;
}
public String getName(){
return name;
}
public int getImageId(){
return imageId;
}
}
我们将每一个子项都当做一个实例,每个实例均由图片与文字组成。
为ListView的子项指定布局:
fruit_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/fruit_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/fruit_name"
android:layout_gravity="center"
android:layout_marginLeft="10dip"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
下面创建自定义的适配器,继承ArrayAdapter,泛型指定为Fruit类:
public class FruitAdapter extends ArrayAdapter<Fruit> {
int resourceId;
public FruitAdapter(Context context,int textViewResourceId,List<Fruit> objects){
super(context,textViewResourceId,objects);
resourceId = textViewResourceId;
}
@Override
public View getView(int position,View convertView,ViewGroup parent){
//获取当前项的实例
Fruit fruit = getItem(position);
//获取ListView子项布局的Id
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());
return view;
}
}
自定义适配器主要重写了一组构造函数,用于将上下文、LisView子项布局的id和需要显示的数据传递进来。另外重写了getView()方法,此方法在每个子项滑动到屏幕内时就会被调用。
在主函数中将自定义的适配器通过setAdapter()方法传入listview即可。