Android的ListView――适配器模式
发布时间:2016-12-15 来源:查字典编辑
摘要:安卓中有一个重要的控件ListView,安卓通过让用户实现BaseAdapter类来连接ListView和数据列表,将数据绑定显示在List...
安卓中有一个重要的控件ListView,安卓通过让用户实现BaseAdapter类来连接ListView和数据列表,将数据绑定显示在ListView中。适配器模式连接两个不兼容的接口,使两个不能一起工作的两个接口实现一起工作的功能。
例子通过模仿Android的ListView实现过程来验证适配器模式,类图结构如下:
实现代码:
var Adapter = Class.extend({ listview:null, dataChanged:function(){ if (this.listview != null) { listview.draw(); } }, getView:function(position){ return ""; }, getCount:function(){ return 0; }, getObject:function(index){ return null; } }); var ListView = Class.extend({ id:null, adapter:null, ctor:function(_id){ this.id = _id; }, setAdapter:function(_adapter){ this.adapter = _adapter; _adapter.listview = this; }, setOnItemClick:function(_callback){ this.callback = String(_callback).replace(/^function(\s|\n)+(.+)\((.|\n)+$/,'$2'); }, draw:function(){ var txt = ""; if(this.adapter != null){ for(var i = 0;i < this.adapter.getCount();i++){ txt += "<div onclick = '" + this.callback + "(" + i + ")"+ "' >" + this.adapter.getView(i) + "</div >"; } } document.getElementById(this.id).innerHTML = txt; } }); var MyAdapter = Adapter.extend({ bean:[], ctor:function(_data){ this.bean = _data }, getCount:function(){ return this.bean.length; }, getView:function(position){ var data = this.bean[position]; var tmpl = "<div class = 'row' ><div class = 'col-xs-3' >姓名</div ><div class = 'col-xs-7' style = 'text-align:right' >${name}</div ></div ><div class = 'row' ><div class = 'col-xs-4' >${sex}</div ><div class = 'col-xs-4' >${age}</div ><div class = 'col-xs-4' >${address}</div ></div >"; while(tmpl.indexOf("${") > 0){ var start = tmpl.indexOf("${"); var end = tmpl.indexOf("}"); var key = tmpl.substring(start,end+1); tmpl = tmpl.replace(key,data[key.replace("${","").replace("}","")]); } return tmpl; }, getObject:function(position){ return bean[position]; } }); <body > <button onclick = "loadData()" >加载数据</button > <div id = "listview" > </div > </body > <script > var beans = [{name:'小红',sex:'女',age:11,address:"厦门"},{name:'小明',sex:'男',age:12,address:'温州'}]; var myAdapter = null; var listview = null; (function(){ myAdapter = new MyAdapter(beans); listview = new ListView("listview"); listview.setAdapter(myAdapter); })(); function loadData(){ myAdapter.dataChanged(); } </script >
运行的效果图:
适配器模式的优点主要是将两个没有关联的类连接在一起,提高了复用,正如上面的例子ListView作为列表可以用在任何场合,数据类也可以在任何场合下继续使用,适配器将两者连接成整体工作达到效果。
适配器过多会造成系统的混乱,不易于程序的可读性。