首页 > 技术文章 > 关于SimpleAdapter和ListView结合使用,实现列表视图的笔记

TheTinkerJ 2016-07-29 14:23 原文

使用ListView需要为其添加适配器:

  适配器有两种:1.ArrayAdapter   --用于单独文字显示

         2.SimpleAdapter --用于文字和图片显示

  这里主要记录SimpleAdapter:

    先看SimpleAdapter的构造函数:

  SimpleAdapter(context,data,resource,from,to)

  --context:上下文,其实就是指的activity本身

  --data:数据源:一个包含了map的List集合;List里的每一个元素都是一个Map集合,Map是包含多组键值对

  --resource:布局文件,可以自己写,在R.Layout下可以获得,布局中对应元素的总和,全部可以储存在Map中

  --from:一个String[]数组,对应Map中的key元素的,类似于起名字 

  --to:在从Map中获取对应key的值后,储存进去具体的值

  下面是具体的例子

  工具:Android studio

  首先写布局文件:item.xml,存放在layou文件夹下

  

<?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/itempic"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:src="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/itemtext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="demo"
        android:textSize="40sp" />
</LinearLayout>

 

  在MainActivity下实例接收ListView和SimpleAdapter对象

private ListView listView;
   // private ArrayAdapter<String> adapter;
    private SimpleAdapter si_adapter;
    //list集合是抽象集合,实例化其实例对象ArrayList
    private List<Map<String,Object>> simpleData;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView)findViewById(R.id.listView);
        simpleData=new ArrayList<Map<String,Object>>();
        si_adapter=new SimpleAdapter(this,getData(),R.layout.item,new String[]{"pic","text"},new int[]{R.id.itempic,R.id.itemtext});
        listView.setAdapter(si_adapter);
    }

  上面的getdate()方法:

   public List<Map<String,Object>> getData(){

        for(int i=0;i<20;i++){
            Map<String,Object> map=new HashMap<String,Object>();
        //填入真实的pic信息 map.put(
"pic",R.mipmap.ic_launcher);
        //填入真实的text信息 map.put(
"text","机器人"+i+"号"); simpleData.add(map); } return simpleData; }

  将SimpleAdapter适配器添加到ListView中去。

  分析:SimpleAdapter对数据的解析

  布局文件:决定的数据的视图化呈现方式

  from:为每一个元素限定一个特定的符号

  to:  每一个元素在XML中的对应情况

  data:数据源,将用于被解析

推荐阅读