在网上看到的,觉得很好,收藏了。原网址:http://www.cnblogs.com/xilinch/archive/2012/11/08/2760233.html
listview
A view that shows items in a vertically scrolling list 。一个显示一个垂直的滚动子项的列表视图
在android开发中,使用listview的地方很多,用它来展现数据,成一个垂直的视图。使用listview是一个标准的适配器模式,用数据--,界面--xml以及适配器--adapter,数据被适配器按照需要的方式展现出来,xml描写了数据如何展现,activity中控制这些活动。
其中使用自定义的adapter,会要重写getView方法,在getView方法产生给用户item的视图以及数据。
这里有一个优化的地方,就是重用view,这样减少内存消耗,同时加快item加载速度。
在getView中优化的地方,大家想必都非常情况,下面我总结了三种优化的写法,请大家指正。
<span style="font-family:Microsoft YaHei;">public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(context).inflate(R.layout.section_list_item1, null); } TextView tv_name = (TextView)convertView.findViewById(R.id.contact_contactinfoitem_tv_name); TextView tv_phone = (TextView)convertView.findViewById(R.id.contact_contactinfoitem_tv_phoneNum); ContactInfo1 confo = contacts.get(position); if (confo != null) {//to set every item's text tv_name.setText(confo.getContactName()); tv_phone.setText(confo.getContact_Phone()); } return convertView; }</span>
<span style="font-family:Microsoft YaHei;">public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder ; if (convertView == null) { convertView = LayoutInflater.from(context).inflate(R.layout.section_list_item1, null); holder = new ViewHolder(); holder.tv_name = (TextView)convertView.findViewById(R.id.contact_contactinfoitem_tv_name); holder.tv_phone = (TextView)convertView.findViewById(R.id.contact_contactinfoitem_tv_phoneNum); convertView.setTag(holder); } else { holder = (ViewHolder)convertView.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 convertView; } class ViewHolder { TextView tv_name,tv_phone; }</span>
<span style="font-family:Microsoft YaHei;">@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; } class ViewHolder { TextView tv_name,tv_phone; }</span>