1.概念
Adapter是连接后端数据和前端显示的适配器接口,是数据和UI(View)之间一个重要的纽带。在常见的View(ListView,GridView)等地方都需要用到Adapter。如下图直观的表
达了Data、Adapter、View三者的关系:
Android中所有的Adapter一览:
2.应用案例
1)ArrayAdapter
列表的显示需要三个元素:
a.ListVeiw 用来展示列表的View。
b.适配器 用来把数据映射到ListView上的中介。
c.数据 具体的将被映射的字符串,图片,或者基本组件。
首先,在这里我们使用fragment来动态加载数据,并没有使用Listview,也是为了熟悉一下fragment知识
我们先来处理一下fragment,这些小的fragment将填充到FrameLayout。
<TextView
android:id="@+id/text01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="序号" />
<TextView
android:id="@+id/list_item_service_text02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="会员姓名" />
<TextView
android:id="@+id/list_item_service_text03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="会员卡号"
/>
接着写一个布局来存放这些fragment
<FrameLayout
android:id="@+id/fragmentContainer_service"
android:layout_width="match_parent"
android:layout_height="match_parent" />
接着我们来写一个activity来托管这些fragement,创建一个FragmentManager的实例,判断主容器是否为空 如果为空则实例一个fragment填充到主容器中
FragmentManager fm = getFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragmentContainer_service);
if (fragment == null) {
fragment = new ServiceListFragment();
fm.beginTransaction().add(R.id.fragmentContainer_service, fragment)
.commit();
}
我们继续写一个ListFragment 主要是写getview方法, 需要返回一个view, 这里写了一个匿名类来调父类方法来绑定数据。convertView是容器中已经存在的view,通过判断容器是否已经有缓存来选择是否加载view,优化性能。
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mService = ServiceLab.get(getActivity()).getServices();
ServiceAdapter adapter = new ServiceAdapter(mService);
setListAdapter(adapter);
}
private class ServiceAdapter extends ArrayAdapter<Service> {
public ServiceAdapter(ArrayList<Service> services) {
super(getActivity(), 0, services);
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getActivity().getLayoutInflater().inflate(
R.layout.list_item_service, null);
}
Service s = getItem(position);
return convertView;
}
}
到这里我们基本完成了Fragment的动态加载,和Adapter。
注意 我没有放ServiceLab类,这段为数据存储,为fragment填充数据。