1.SimpleAdapter
上一篇博客介绍的ArrayAdapter只能接受数组作为数据源,一般用于显示一行文字,更复杂的内容的显示可以用SimpleAdapter来实现。
SimpleAdapter接受List<Map<String, Object>>作为数据源,每个Map对应一个item(比如购物车里的一件商品,书架上的一本书),Map中的key需要与视图控件相对应,这样value就可以显示到视图控件中了。
2.SimpleAdapter实现
1)item的layout文件
一个item中显示一张图片和一段text
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/iv_icon"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="70dp"
tools:src = "@drawable/earth"
></ImageView>
<TextView
android:id="@+id/tv_name"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_weight="3"
android:textColor="@color/teal_200"
android:textSize="30dp"
android:text="earth"
android:gravity="center"
></TextView>
</LinearLayout>
2)主界面layout文件
用Spinner作为View容纳item
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".SpinnerActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Spinner using simple adapter"
android:textSize="30dp" />
<Spinner
android:id="@+id/sp_drop"
android:layout_width="match_parent"
android:layout_height="70dp"
android:spinnerMode="dropdown"></Spinner>
</LinearLayout>
3)java文件
对比 ArrayAdapter,SimpleAdapter增加了后两个参数,表明Map<String, Object>中key和item的layout文件中的视图id的对应关系。
SimpleAdapter adapter = new SimpleAdapter(this,list,R.layout.item_icon,
new String[]{"icon", "name"},
&nbs

文章介绍了Android开发中,从简单的ArrayAdapter到更复杂的SimpleAdapter,以及最高灵活性的BaseAdapter的使用。SimpleAdapter适用于显示包含多元素的数据项,而BaseAdapter允许自定义数据源和视图绑定,适配更复杂场景。文章通过示例展示了如何在Spinner中使用这些适配器。
最低0.47元/天 解锁文章
635

被折叠的 条评论
为什么被折叠?



