ListView 及 SimpleAdapter的简单案例

SimpleAdapter是扩展性最好的适配器,可以定义各种你想要的布局,而且使用很方便
SimpleAdapter(Contextcontext, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)

  • 参数context:上下文,比如this。关联SimpleAdapter运行的视图上下文
  • 参数data:Map列表,列表要显示的数据,这部分需要自己实现,如例子中的getData(),类型要与上面的一致,每条项目要与from中指定条目一致
  • 参数resource:ListView单项布局文件的Id,这个布局就是你自定义的布局了,你想显示什么样子的布局都在这个布局中。这个布局中必须包括了to中定义的控件id
  • 参数 from:一个被添加到Map上关联每一个项目列名称的列表,数组里面是列名称
  • 参数 to:是一个int数组,数组里面的id是自定义布局中各个控件的id,需要与上面的from对应
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //[1]找到控件
        ListView lv = (ListView) findViewById(R.id.lv);
        //[1.1]准备listview 要显示的数据
        List<Map<String, String>> data = new ArrayList<Map<String,String>>();
        Map<String, String> map1 = new  HashMap<String, String>();
        map1.put("name", "张飞");
        map1.put("phone", "1388888");
        
        Map<String, String> map2 = new  HashMap<String, String>();
        map2.put("name", "赵云");
        map2.put("phone", "110");
        
        Map<String, String> map3 = new  HashMap<String, String>();
        map3.put("name", "貂蝉");
        map3.put("phone", "13882223");
        
        
        Map<String, String> map4 = new  HashMap<String, String>();
        map4.put("name", "关羽");
        map4.put("phone", "119");
        
        //[1.1]把map加入到集合中
        data.add(map1);
        data.add(map2);
        data.add(map3);
        data.add(map4);
        
        //[2]设置数据适配器  resource 我们定义的布局文件
        // from map集合的键
        SimpleAdapter adapter = new SimpleAdapter(getApplicationContext(), data, R.layout.item,
                new String[]{"name","phone"}, new int[]{R.id.tv_name,R.id.tv_phone});
        
        //[3]设置数据适配器 
        lv.setAdapter(adapter);
        
        
    }

    

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容