在Android开发中,我们常常需要将多条数据排成一列进行展示,这可能需要多个一模一样的重复单元,而这就可以用到我们的ListView控件。

ListView

<ListView
        android:id="@+id/lv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="5dp"
        android:divider="#d9d9d9"
        android:dividerHeight="2dp">
</ListView>

效果

如上,我们在布局文件中定义了一个ListView控件,初始展示的效果如上。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_vertical">
    <ImageView
        android:id="@+id/item_image"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:layout_margin="8dp"
        android:background="@drawable/wx" />
    
    <TextView
        android:id="@+id/item_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Item布局"
        android:textSize="18sp" />
</LinearLayout>

对于单个Item,我们需要新建一个布局去定义它。

而在完成上述控件定义工作之后,我们就可以向控件导入数据了,而这就需要用到数据适配器Adapter了。

Adapter

Android系统中提供了几个常用的数据适配器:

BaseAdapter

BaseAdapter作为基本适配器,其本质上是一个抽象类,需要我们去实现如下几个方法:

  • getCount():获取Item的总数
  • getItem(int position):获取某位置Item对象
  • getItemId(int positon):获取某位置Item的ID
  • getView(int position, View convertView, ViewGroup parent):获取对应位置Item视图

SimpleAdapter

实现了对BaseAdapter封装,仅需创建布局并将ListView绑定到适配器中即可。但是要求数据源是List<?extends Map<String,? >>的形式,即为Map的具体实现,且键的类型要求是String。

ArrayAdapter

另一个适配器,用于适配列表或数组。

在完成对具体适配器的实现后,我们需要将Adapter绑定到ListView上。

listView.setAdapter(Adapter);

常见优化

  • 复用convertView

    由于系统在第一次展示的时候将会根据屏幕宽高自动生成一定数量的convertView,我们可以将超出界面的convertView进行复用,减少不必要的资源浪费。

  • 使用ViewHolder类

    减少findViewById()方法寻找控件ID所造成的的消耗。

Last modification:October 28, 2020
博客维护不易,如果你觉得我的文章有用,请随意赞赏