ListView优化的代码
第三種ListView優化:通過convertView+ViewHolder來實現,ViewHolder就是一個靜態類,使用 ViewHolder 的關鍵好處是緩存了顯示數據的視圖(View),加快了 UI 的響應速度。
當我們判斷?convertView?==?null??的時候,如果為空,就會根據設計好的List的Item布局(XML),來為convertView賦值,并生成一個viewHolder來綁定converView里面的各個View控件(XML布局里面的那些控件)。再用convertView的setTag將viewHolder設置到Tag中,以便系統第二次繪制ListView時從Tag中取出。(看下面代碼中)
如果convertView不為空的時候,就會直接用convertView的getTag(),來獲得一個ViewHolder。
?
//在外面先定義,ViewHolder靜態類 static class ViewHolder {public ImageView img;public TextView title;public TextView info; } //然后重寫getView @Overridepublic View getView(int position, View convertView, ViewGroup parent) {ViewHolder holder;if(convertView == null){holder = new ViewHolder();convertView = mInflater.inflate(R.layout.list_item, null);holder.img = (ImageView)item.findViewById(R.id.img) holder.title = (TextView)item.findViewById(R.id.title);holder.info = (TextView)item.findViewById(R.id.info);convertView.setTag(holder);}else{holder = (ViewHolder)convertView.getTag();}holder.img.setImageResource(R.drawable.ic_launcher);holder.title.setText("Hello");holder.info.setText("World");return convertView;}到這里,可能會有人問ViewHolder靜態類結合緩存convertView與直接使用convertView有什么區別嗎,是否重復了
在這里,官方給出了解釋
提升Adapter的兩種方法
To work efficiently the adapter implemented here uses two techniques:
-It reuses the convertView passed to getView() to avoid inflating View when it is not necessary
(譯:重用緩存convertView傳遞給getView()方法來避免填充不必要的視圖)
-It uses the ViewHolder pattern to avoid calling findViewById() when it is not necessary
(譯:使用ViewHolder模式來避免沒有必要的調用findViewById():因為太多的findViewById也會影響性能)
ViewHolder類的作用
-The ViewHolder pattern consists in storing a data structure in the tag of the view
returned by getView().This data structures contains references to the views we want to bind data to,
thus avoiding calling to findViewById() every time getView() is invoked
(譯:ViewHolder模式通過getView()方法返回的視圖的標簽(Tag)中存儲一個數據結構,這個數據結構包含了指向我們
要綁定數據的視圖的引用,從而避免每次調用getView()的時候調用findViewById())
?
轉載于:https://www.cnblogs.com/zhoujn/p/4108747.html
總結
以上是生活随笔為你收集整理的ListView优化的代码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: swap的几点理解
- 下一篇: Ueditor1.4.3上传视频IE下无