SimpleAdapter(简单适配器):这个适配器不要被名字迷惑,看是简单,但功能强大
<?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="vertical">
<ListView
android:id="@+id/ll1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
定义要实现的item的样式 layout文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="@+id/image1"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@mipmap/ic_launcher"
android:layout_margin="5dp"/>
<LinearLayout
android:id="@+id/ll2"
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="vertical"
android:layout_marginTop="5dp"
android:layout_marginLeft="10dp">
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="哈哈"
android:textSize="30sp"
android:layout_marginTop="10dp"/>
<TextView
android:id="@+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="哈哈哈哈哈"
android:textSize="24dp"
android:layout_marginTop="10dp"/>
</LinearLayout>
</LinearLayout>
Java文件
package com.example.test3;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends Activity{
// 这三个经常是同时出现的
private List<Map<String,Object>> lists;
private SimpleAdapter adapter;
private ListView listView;
// 定义数据
private String[] theme = {"张三","李四","王五"};
private String[] content ={"我是张三,你好","我是李四,你好","我是王五,你好"};
private int[] imageViews = {R.mipmap.ic_launcher,R.mipmap.ic_account,R.mipmap.ic_password};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.ll1);
// 准备数据源
lists = new ArrayList<>();
for(int i = 0;i < theme.length;i++){
Map<String,Object> map =new HashMap<>();
map.put("image",imageViews[i]);
map.put("theme",theme[i]);
map.put("content",content[i]);
lists.add(map);
}
adapter = new SimpleAdapter(MainActivity.this,lists,R.layout.list_item
,new String[]{"image","theme","content"}
,new int[]{R.id.image1,R.id.text1,R.id.text2});
listView.setAdapter(adapter);
}
}
效果图:
(2)simpleAdapter中五个参数的
第一个参数:上下文对象
第二个参数:数据源是含有Map的一个集合
第三个参数:每一个item的布局文件
第四个参数:new String[]{}数组,数组的里面的每一项要与第二个参数中的存入map集合的的key值一样,一一对应
第五个参数:new int[]{}数组,数组里面的第三个参数中的item里面的控件id。