官方定义: Displays a vertically-scrollable collection of views, where each view is positioned immediately below the previous view in the list. For a more modern, flexible, and performant approach to displaying lists, use RecyclerView .
翻译 :显示一个垂直可滚动的视图集合,其中每个视图都位于列表中前一个视图的下方。要获得更现代、更灵活、更高效的显示列表的方法,请使用RecyclerView。
【课前了解——Adapter适配器】
是连接后端数据和前端显示的适配器接口,是数据和UI(View视图)之间的纽带和桥梁。
在数据适配器中设置数据,那么设置item的视图,常用的数据适配器如下BaseAdapter、SimpleAdapter、ArrayAdapter
BaseAHapter:抽象类,有四个抽象方法
getcount | 获取适配器中数据项的数量 |
getltem | 获取指定位置的数据项 |
get ltemid | 返回指定位置的数据项的唯一标识符,通常使用数据项的ID 或 位置索引作为标识符 |
getView | 获取指定位置的数据项的视图 |
ListView使用步骤
一、xml中,添加ListView
二、准备数据
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="15dp"
>
<ImageView
android:id="@+id/image"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_centerVertical="true"
/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginStart="10dp"
android:layout_toEndOf="@+id/image">
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="苹果"
android:textSize="30sp"
/>
<TextView
android:id="@+id/tv_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:text="价格"
android:layout_below="@+id/name"
android:layout_marginTop="10dp"
/>
<TextView
android:id="@+id/num_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:text="1"
android:layout_below="@+id/name"
android:layout_toEndOf="@+id/tv_price"
android:layout_marginTop="10dp"
/>
</RelativeLayout>
</RelativeLayout>
三、创建Adapter
(1)让Adapter类继承与BaseAdapter,实现其方法
class listView_Adapter extends BaseAdapter {
@Override
public int getCount() {
return names.length;
}
@Override
public Object getItem(int position) {
return names[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return null;
}
}
(2)重点在getView
四、关联ListView和Adapter (setAdapter)