用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>
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦