高效 list adapter

本文介绍了一个关于编写高效ListViewAdapter的Android demo,通过复用convertView和使用ViewHolder模式来提高ListView的性能。
Android api demo里面有一个编写高效list adapter的demo,里面写了建议的两条高效原则

1. 在getView方法中,重复利用 convertView,convertView是旧的View,建议先判断是否为空,如果不为空,可以修改其内容来显示新的row。


public View getView(int position, View convertView, ViewGroup parent) {
SpeechView sv;
if (convertView == null) {
sv = new SpeechView(mContext, mTitles[position],
mDialogue[position]);
} else {
sv = (SpeechView) convertView;
sv.setTitle(mTitles[position]);
sv.setDialogue(mDialogue[position]);
}

return sv;
}


2. 在getView方法中,利用ViewHolder来保存与convertView相关联的子View,避免调用 findViewById方法,以提高效率


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();
}

holder.text.setText(DATA[position]);
holder.icon.setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2);

return convertView;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值