利用ViewHolder优化自定义Adapter的典型写法
1 public class MarkerItemAdapter extends BaseAdapter
{
private Context mContext = null;
private List<MarkerItem> mMarkerData = null; public MarkerItemAdapter(Context context, List<MarkerItem> markerItems)
{
mContext = context;
mMarkerData = markerItems;
} public void setMarkerData(List<MarkerItem> markerItems)
{
mMarkerData = markerItems;
} @Override
public int getCount()
{
int count = 0;
if (null != mMarkerData)
{
count = mMarkerData.size();
}
return count;
} @Override
public MarkerItem getItem(int position)
{
MarkerItem item = null; if (null != mMarkerData)
{
item = mMarkerData.get(position);
} return item;
} @Override
public long getItemId(int position)
{
return position;
} @Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder viewHolder = null;
if (null == convertView)
{
viewHolder = new ViewHolder();
LayoutInflater mInflater = LayoutInflater.from(mContext);
convertView = mInflater.inflate(R.layout.item_marker_item, null); viewHolder.name = (TextView) convertView.findViewById(R.id.name);
viewHolder.description = (TextView) convertView
.findViewById(R.id.description);
viewHolder.createTime = (TextView) convertView
.findViewById(R.id.createTime); convertView.setTag(viewHolder);
}
else
{
viewHolder = (ViewHolder) convertView.getTag();
} // set item values to the viewHolder: MarkerItem markerItem = getItem(position);
if (null != markerItem)
{
viewHolder.name.setText(markerItem.getName());
viewHolder.description.setText(markerItem.getDescription());
viewHolder.createTime.setText(markerItem.getCreateDate());
} return convertView;
} private static class ViewHolder
{
TextView name;
TextView description;
TextView createTime;
} }
convertView及缓存的View,若convertView!=null,则不必反射view。viewHolder是一个内部类,用于对控件的实例进行缓存。当convertView为空时,创建一个ViewHolder对象,并将控件的实例都存放在ViewHolder中,然后调用View的setTag()方法,将ViewHolder对象存储在View中。当convertView不为空时则调用View的getTag()方法,把ViewHolder重新取出。
其中MarkerItem是自定义的类,其中包含name,description,createTime等字段,并且有相应的get和set方法。
ViewHolder是一个内部类,其中包含了单个项目布局中的各个控件。
单个项目的布局,即R.layout.item_marker_item如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="5dp"> <TextView
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Name"
android:textSize="20sp"
android:textStyle="bold" /> <TextView
android:id="@+id/description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Description"
android:textSize="18sp" /> <TextView
android:id="@+id/createTime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="CreateTime"
android:textSize="16sp" /> </LinearLayout>
官方的API Demos中也有这个例子:
package com.example.android.apis.view中的List14:
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ package com.example.android.apis.view; import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.ImageView;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap;
import com.example.android.apis.R; /**
* Demonstrates how to write an efficient list adapter. The adapter used in this example binds
* to an ImageView and to a TextView for each row in the list.
*
* 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
* - It uses the ViewHolder pattern to avoid calling findViewById() when it is not necessary
*
* 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 calls to findViewById() every time getView() is invoked.
*/
public class List14 extends ListActivity { private static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private Bitmap mIcon1;
private Bitmap mIcon2; public EfficientAdapter(Context context) {
// Cache the LayoutInflate to avoid asking for a new one each time.
mInflater = LayoutInflater.from(context); // Icons bound to the rows.
mIcon1 = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon48x48_1);
mIcon2 = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon48x48_2);
} /**
* The number of items in the list is determined by the number of speeches
* in our array.
*
* @see android.widget.ListAdapter#getCount()
*/
public int getCount() {
return DATA.length;
} /**
* Since the data comes from an array, just returning the index is
* sufficent to get at the data. If we were using a more complex data
* structure, we would return whatever object represents one row in the
* list.
*
* @see android.widget.ListAdapter#getItem(int)
*/
public Object getItem(int position) {
return position;
} /**
* Use the array index as a unique id.
*
* @see android.widget.ListAdapter#getItemId(int)
*/
public long getItemId(int position) {
return position;
} /**
* Make a view to hold each row.
*
* @see android.widget.ListAdapter#getView(int, android.view.View,
* android.view.ViewGroup)
*/
public View getView(int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid unneccessary calls
// to findViewById() on each row.
ViewHolder holder; // When convertView is not null, we can reuse it directly, there is no need
// to reinflate it. We only inflate a new View when the convertView supplied
// by ListView is null.
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item_icon_text, null); // Creates a ViewHolder and store references to the two children views
// we want to bind data to.
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
holder.icon = (ImageView) convertView.findViewById(R.id.icon); convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
} // Bind the data efficiently with the holder.
holder.text.setText(DATA[position]);
holder.icon.setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2); return convertView;
} static class ViewHolder {
TextView text;
ImageView icon;
}
} @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new EfficientAdapter(this));
} private static final String[] DATA = Cheeses.sCheeseStrings;
}
其中布局:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2007 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"> <ImageView android:id="@+id/icon"
android:layout_width="48dip"
android:layout_height="48dip" /> <TextView android:id="@+id/text"
android:layout_gravity="center_vertical"
android:layout_width="0dip"
android:layout_weight="1.0"
android:layout_height="wrap_content" /> </LinearLayout>
转自:http://www.cnblogs.com/mengdd/p/3254323.html
利用ViewHolder优化自定义Adapter的典型写法的更多相关文章
- Android中利用ViewHolder优化自定义Adapter的典型写法
利用ViewHolder优化自定义Adapter的典型写法 最近写Adapter写得多了,慢慢就熟悉了. 用ViewHolder,主要是进行一些性能优化,减少一些不必要的重复操作.(WXD同学教我的. ...
- adapter-自定义adapter的典型写法
文章参考 http://www.cnblogs.com/mengdd/p/3254323.html import android.content.Context; import android.vie ...
- android代码优化----ListView中自定义adapter的封装(ListView的模板写法)
[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...
- 【转】 Pro Android学习笔记(二二):用户界面和控制(10):自定义Adapter
目录(?)[-] 设计Adapter的布局 代码部分 Activity的代码 MyAdapter的代码数据源和构造函数 MyAdapter的代码实现自定义的adapter MyAdapter的代码继续 ...
- listview的ViewHolder优化
1.自定义listview,首先在activity.xml中插入一个listview,可以用android:divider=""设置分割线颜色样式,android:dividerH ...
- android 自定义adapter和线程结合 + ListView中按钮滑动后状态丢失解决办法
adapter+线程 1.很多时候自定义adapter的数据都是来源于服务器的,所以在获取服务器的时候就需要异步获取,这里就需要开线程了(线程池)去获取服务器的数据了.但这样有的时候adapter的中 ...
- 利用反射跟自定义注解拼接实体对象的查询SQL
前言 项目中虽然有ORM映射框架来帮我们拼写SQL,简化开发过程,降低开发难度.但难免会出现需要自己拼写SQL的情况,这里分享一个利用反射跟自定义注解拼接实体对象的查询SQL的方法. 代码 自定义注解 ...
- [Android] Android RecycleView和ListView 自定义Adapter封装类
在网上查看了很多对应 Android RecycleView和ListView 自定义Adapter封装类 的文章,主要存在几个问题: 一).网上代码一大抄,复制来复制去,大部分都运行不起来,或者 格 ...
- Android 自定义Adapter实现多视图Item的ListView
自定义Adapter实现多视图Item的ListView http://www.devdiv.com/adapter_item_listview-blog-20-7539.html 1.原理分析 Ad ...
随机推荐
- Volley网络连接
一.Volley a burst or emission of many things or a large amount at once Volley是Android平台上的网络通信库,能使网络通信 ...
- Struts2原理
Struts 2以WebWork优秀的设计思想为核心,吸收了Struts 1的部分优点,建立了一个兼容WebWork和Struts 1的MVC框架,Struts 2的目标是希望可以让原来使用Strut ...
- iOSQuartz2D-03-定制个性头像
效果图 将一张图片剪切成圆形 在图片周围显示指定宽度和颜色的边框 实现思路 效果图中主要由不同尺寸的两大部分组成 蓝色的背景区域,尺寸等于图片的尺寸加上边框的尺寸 图片区域,尺寸等于图片的尺寸 绘制一 ...
- OC语言-05-OC语言-内存管理
一.引用计数器 1> 栈和堆 栈 ① 主要存储局部变量 ② 内存自动回收 堆 ① 主要存储需要动态分配内存的变量 ② 需要手动回收内存,是OC内存管理的对象 2> 简介 作用 ① 表示对象 ...
- XML学习总结(一)——XML介绍
一.XML概念 Extensible Markup Language,翻译过来为可扩展标记语言.Xml技术是w3c组织发布的,目前推荐遵循的是W3C组织于2000发布的XML1.0规范. 二.学习XM ...
- PHP模拟发送POST请求之二、用PHP和JS处理URL信息
明白了HTTP请求的头信息后,我们还需要对请求地址有所了解.再者,HTTP GET请求是靠URL实现的,所以了解URL的构造,处理URL的重要性不言而喻. 在PHP中我们用parse_url()函数来 ...
- MFC添加右键菜单
本文原创转载请注明作者及出处 本文链接:http://blog.csdn.net/wlsgzl/article/details/42147277 --------------------------- ...
- cocos2d-x之事件传递
bool HelloWorld::init() { if ( !Layer::init() ) { return false; } Size size=Director::getInstance()- ...
- Beeline known issues
If you use nohup myscript.sh , You beeline scripts may not work, Pay attention to this in your job.
- UESTC 915 方老师的分身II --最短路变形
即求从起点到终点至少走K条路的最短路径. 用两个变量来维护一个点的dis,u和e,u为当前点的编号,e为已经走过多少条边,w[u][e]表示到当前点,走过e条边的最短路径长度,因为是至少K条边,所以大 ...