Android中利用ViewHolder优化自定义Adapter的写法(必看)
发布时间 - 2026-01-11 00:42:17 点击率:次最近写Adapter写得多了,慢慢就熟悉了。

用ViewHolder,主要是进行一些性能优化,减少一些不必要的重复操作。(WXD同学教我的。)
具体不分析了,直接上一份代码吧:
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;
}
}
其中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>
以上这篇Android中利用ViewHolder优化自定义Adapter的写法(必看)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
# adapter
# viewholder
# Android自定义实现BaseAdapter的优化布局
# android listview优化几种写法详细介绍
# Android开发中ListView自定义adapter的封装
# Android自定义Adapter的ListView的思路及代码
# 给大家
# 自定义
# 是一个
# 也有
# 希望能
# 得多
# 这篇
# 教我
# 必看
# 小编
# 大家多多
# 主要是
# 其中包含
# 上一份
# 有相应
# 包含了
# schemas
# apk
# res
# xmlns
相关栏目:
【
网站优化151355 】
【
网络推广146373 】
【
网络技术251813 】
【
AI营销90571 】
相关推荐:
如何自定义建站之星网站的导航菜单样式?
如何用AI一键生成爆款短视频文案?小红书AI文案写作指令【教程】
Laravel N+1查询问题如何解决_Eloquent预加载(Eager Loading)优化数据库查询
laravel怎么为应用开启和关闭维护模式_laravel应用维护模式开启与关闭方法
Laravel如何处理跨站请求伪造(CSRF)保护_Laravel表单安全机制与令牌校验
html文件怎么打开证书错误_https协议的html打开提示不安全【指南】
高端网站建设与定制开发一站式解决方案 中企动力
html5源代码发行怎么设置权限_访问权限控制方法与实践【指南】
Laravel如何设置自定义的日志文件名_Laravel根据日期或用户ID生成动态日志【技巧】
Laravel如何使用Blade模板引擎?(完整语法和示例)
Laravel如何处理CORS跨域请求?(配置示例)
魔方云NAT建站如何实现端口转发?
Laravel用户密码怎么加密_Laravel Hash门面使用教程
Linux网络带宽限制_tc配置实践解析【教程】
如何用PHP快速搭建高效网站?分步指南
香港服务器网站测试全流程:性能评估、SEO加载与移动适配优化
如何在阿里云虚拟机上搭建网站?步骤解析与避坑指南
Python制作简易注册登录系统
如何续费美橙建站之星域名及服务?
专业商城网站制作公司有哪些,pi商城官网是哪个?
详解jQuery停止动画——stop()方法的使用
百度输入法ai组件怎么删除 百度输入法ai组件移除工具
Java类加载基本过程详细介绍
ChatGPT怎么生成Excel公式_ChatGPT公式生成方法【指南】
如何快速辨别茅台真假?关键步骤解析
,南京靠谱的征婚网站?
如何用JavaScript实现文本编辑器_光标和选区怎么处理
瓜子二手车官方网站在线入口 瓜子二手车网页版官网通道入口
HTML5空格和margin有啥区别_空格与外边距的使用场景【说明】
Laravel如何实现全文搜索功能?(Scout和Algolia示例)
Win11任务栏卡死怎么办 Windows11任务栏无反应解决方法【教程】
微信公众帐号开发教程之图文消息全攻略
如何在HTML表单中获取用户输入并结合JavaScript动态控制复利计算循环
Java解压缩zip - 解压缩多个文件或文件夹实例
Laravel怎么为数据库表字段添加索引以优化查询
Laravel怎么做数据加密_Laravel内置Crypt门面的加密与解密功能
Laravel如何实现密码重置功能_Laravel密码找回与重置流程
佛山企业网站制作公司有哪些,沟通100网上服务官网?
Laravel中的withCount方法怎么高效统计关联模型数量
北京企业网站设计制作公司,北京铁路集团官方网站?
Java垃圾回收器的方法和原理总结
西安市网站制作公司,哪个相亲网站比较好?西安比较好的相亲网站?
Laravel怎么使用Collection集合方法_Laravel数组操作高级函数pluck与map【手册】
网站设计制作书签怎么做,怎样将网页添加到书签/主页书签/桌面?
如何在万网利用已有域名快速建站?
Laravel Eloquent关联是什么_Laravel模型一对一与一对多关系精讲
如何在万网主机上快速搭建网站?
微信小程序 配置文件详细介绍
重庆市网站制作公司,重庆招聘网站哪个好?
详解免费开源的.NET多类型文件解压缩组件SharpZipLib(.NET组件介绍之七)

