What are Adapters and when and how are they used?

Refer to P181 The adapter is responsible for:

  • creating the necessary view object;
  • bind view with data from the model layer;
  • returning the view object to the ListView.

为ListFragment创建默认的ArrayAdapter:

  1. ListView只有在需要显示某些列表项时,它才会去申请可用的视图对象;如果为所有的列表项数据创建视图对象,会浪费内存;

    Lists can be enormous, and unnecessarily creating and storing view objects for an entire list could cause performance and memory problems. The wiser course is to create view objects only as they are needed. The ListView asks for a view object when it needs to display a certain list item.

  2. ListView找谁去申请视图对象呢? 答案是adapter。adapter是一个控制器对象,负责从模型层获取数据,创建并填充必要的视图对象,将准备好的视图对象返回给ListView;

    Whom does the ListView ask? It asks its adapter. An adapter is a controller object that bridge the View (e.g. ListView, GridView, RecyclerView and ViewPager) and Model (the data set containing the data that the ListView should display).

  3. 首先,通过调用adapter的getCount()方法,ListView询问数组列表中包含多少个对象(为避免出现数组越界的错误);紧接着ListView就调用adapter的getView(int, View, ViewGroup)方法。

    • android.R.layout.simple_list_item_1 是Android SDK提供的列表项的布局资源,仅包含一个TextView;
    • 默认的toString()方法等价于getClass().getName() + '@' + Integer.toHexString(hashCode()),返回了混和对象类名和内存地址的字符串信息。

用例: ListFragment with ArrayAdapter commit