Listview的自定义界面的使用

listview的使用在这里就不说了,直接说listview定制界面的使用。

1.定义一个实体类,作为listview的适配器的适配类型

新建类Fruit,代码如下:

public class Fruit {
    private String name; 
    private int imageId; //图片id
    public Fruit(String name, int imageId) {
        this.name = name;
        this.imageId = imageId;
    }
    public String getName() {
        return name;
    }
    public int getImageId() {
        return imageId;
    }
}

2.定义listview的布局

建立fruit_item.cml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
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_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginLeft="10dip" />
</LinearLayout>

在这个布局中,我们定义了一个 ImageView 用于显示水果的图片,又定义了一个TextView 用于显示水果的名称。

3.创建一个自定义的适配器,这个适配器继承自ArrayAdapter,并将泛型指定为 Fruit 类
新建类FruitAdapter:

public class FruitAdapter extends ArrayAdapter<Fruit> {
    private 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); // 获取当前项的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); 
    /*以下代码一定要注意参数类型(第一个为int,第二个为string),否则会闪退,虽然是个小问题,一旦出错确实很难发现*/
    fruitImage.setImageResource(fruit.getImageId());
    fruitName.setText(fruit.getName());

    return view;
}
}

FruitAdapter 重写了父类的一组构造函数,用于将上下文、ListView 子项布局的 id 和数据都传递进来。另外又重写了 getView()方法,这个方法在每个子项被滚动到屏幕内的时候会被调用。在 getView 方法中,首先通过 getItem()方法得到当前项的 Fruit 实例,然后使用LayoutInflater 来为这个子项加载我们传入的布局,接着调用 View 的 findViewById()方法分别获取到 ImageView 和 TextView 的实例,并分别调用它们的 setImageResource()和 setText()方法来设置显示的图片和文字,最后将布局返回。

4.MainActivity的调用
(1)新建Fruit类型的List
private List fruitList = new ArrayList();

(2)在 onCreate()方法中添加数据,
Fruit apple = new Fruit(“Apple”,R.drawable.apple_pic);
fruitList.add(apple);
Fruit banana = new Fruit(“Banana”,R.drawable.banana_pic);
fruitList.add(banana);
Fruit orange = new Fruit(“Orange”,R.drawable.orange_pic);
fruitList.add(orange);

。。。。。。
(3)在 onCreate()方法中创建 FruitAdapter 对象,并将 FruitAdapter 作为适配器传递给了 ListView:
FruitAdapter adapter = new FruitAdapter(MainActivity.this,R.layout.fruit_item, fruitList);

(4)
ListView listView = (ListView) findViewById(R.id.list_view);
listView.setAdapter(adapter);

转自《第一行代码》。

猜你喜欢

转载自blog.csdn.net/qq_40712616/article/details/79185258