您好,登錄后才能下訂單哦!
安卓中有一個重要的控件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作為列表可以用在任何場合,數據類也可以在任何場合下繼續使用,適配器將兩者連接成整體工作達到效果。
適配器過多會造成系統的混亂,不易于程序的可讀性。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。