在Android应用的开发中,很多地方都会用到ListView,方便快捷的展示数据。但是当展示的数据非常大量的话,界面就会卡。
(1)在android中,加载一个view对象是非常耗内存的,所以在getView方法中要重用Item的View对象ConvertView,减少内存的使用,提高Item加载的速度。
(2)重用在Item子项中要显示的子view对象,不需要每次都调用findViewByid()。
先上代码:
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
View view = convertView;
ViewHolder holder ;
if (view == null) {
view = LayoutInflater.from(context).inflate(R.layout.section_list_item1, null);
holder = new ViewHolder();
holder.tv_name = (TextView)view.findViewById(R.id.contact_contactinfoitem_tv_name);
holder.tv_phone = (TextView)view.findViewById(R.id.contact_contactinfoitem_tv_phoneNum);
view.setTag(holder);
}
else
{
holder = (ViewHolder)view.getTag();
}
ContactInfo1 confo = contacts.get(position);
Log.i("my", "confo "+confo.getContactName());
if (confo != null) {//to set every item's text
holder.tv_name.setText(confo.getContactName());
holder.tv_phone.setText(confo.getContact_Phone());
}
return view;
}
static class ViewHolder
{
TextView tv_name,tv_phone;
}
重用convertView会节省很多内存,当listview加载的数据很大时,效果是很明显的,可以让listview滑动的更加顺畅;
上述代码中使用了convertView.setTag(),该方法缓存了viewHolder对象,其实setTag()方法被调用时,也会占用内存;
重用convertView对象会节省很多内存,所以本人觉得不需要使用setTag()方法,并且ViewHolder类(静态内部类)只会初始化一次,只会有一个viewholder对象,这也节省了内存的消耗,去掉setTag()方法的代码如下:
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
View view = convertView;
ViewHolder holder ;
if (view == null) {
view = LayoutInflater.from(context).inflate(R.layout.section_list_item1, null);
holder = new ViewHolder();
holder.tv_name = (TextView)view.findViewById(R.id.contact_contactinfoitem_tv_name);
holder.tv_phone = (TextView)view.findViewById(R.id.contact_contactinfoitem_tv_phoneNum);
}
ContactInfo1 confo = contacts.get(position);
Log.i("my", "confo "+confo.getContactName());
if (confo != null) {//to set every item's text
holder.tv_name.setText(confo.getContactName());
holder.tv_phone.setText(confo.getContact_Phone());
}
return view;
}
static class ViewHolder
{
TextView tv_name,tv_phone;
}