那些复杂的列表总要弄个清楚——(二)用SimpleAdapter做适配器

来源:互联网 发布:野野村龙太郎 知乎 编辑:程序博客网 时间:2024/06/04 04:43

每次看到QQ和微信的列表都觉得挺棒的,

实现一个写死了的列表。


首先,布局文件里要有一个ListView。

<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:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.example.listview2.MainActivity"     android:orientation="vertical"    android:background="#fff">    <ListView         android:id="@+id/lv"        android:layout_width="match_parent"        android:layout_height="0dp"        android:layout_weight="1"        android:dividerHeight="5dp"        android:divider="@android:color/white"></ListView></LinearLayout>


ListView中的divider是分割线,就是一个个列表项的分割线,可以自己设置高度和颜色,我直接设了白色

然后应该有一个单个列表项的布局文件,再layout文件夹下新建一个single.xml


single.xml布局如下:

<?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:orientation="horizontal" >        <ImageView         android:id="@+id/imgv"        android:layout_width="50dp"        android:layout_height="50dp"/>        <TextView         android:id="@+id/tv"        android:layout_width="0dp"        android:layout_weight="1"        android:layout_height="wrap_content"        android:gravity="center"        android:textSize="20sp"/></LinearLayout>

一个ImageView和一个TextView


然后在java代码中,

ListView lv;lv = (ListView)findViewById(R.id.lv);

接下来新建两个数组,一个存放图片资源id,另一个存放字符串

int[] image = {R.drawable.pic1, R.drawable.pic2, R.drawable.pic3, R.drawable.pic4, R.drawable.pic5};String[] text = {"我饿了", "最近近视有点深", "但是还是活力满满", "减肥减成一头熊", "还是去上班好了"};

再新建一个List<Map<String, Object>>类型的items,这个要用于后面构造SimpleAdapter适配器

List<Map<String, Object>> items = new ArrayList<Map<String, Object>>();for(int i = 0; i<5; i++) {Map<String, Object> item = new HashMap<String, Object>();item.put("img", image[i]);item.put("text", text[i]);items.add(item);}


看看上面这段代码,我们添加了五项,map是键值对,一个key对应一个value,里面的键(“img”和“text”)再构造适配器时也要用到

接下来构造SimpleAdapter,先新建个变量,

SimpleAdapter adapter;
然后看下面这段代码,是构造适配器的:

adapter = new SimpleAdapter(this,          items,          R.layout.single,          new String[] {"img", "text"},          new int[] {R.id.imgv, R.id.tv});

它的第一个参数是context,

第二个参数是存放数据的List<Map<String, Object>>类型的items

第三个参数是单个列表项的布局文件

第四个参数是(from)items里的键,第五个参数是对应的键所存的值应该放置的控件的id

所以第四个参数和第五个参数实际上是一一对应的,例如上述的”img“对应的图片资源id应该作为ImageView的src,“text”对应的字符串应该作为TextView的text。


做出来的效果是这样的:

就酱。



阅读全文
0 0