我们常用ListView,甚至GridView的编写方式也与ListView非常类似,而且GridView往往加载图片,性能问题尤为明显。在ListViewAdapter中使用convertView以及ViewHolder,能提升ListView的性能。
在Adapter中,我们关注比较多的就是getCount()和getView(),getCount()就是计算ListView的个数的,比较简单。下面列举一个简单的GridView以及GridViewAdapter的代码,然后再看看性能哪些地方可做优化。
MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.gridview); mContext = getApplicationContext(); final int reqSize = getResources().getDimensionPixelSize(R.dimen.image_thumbnail_size); GridViewAdapter adapter = new GridViewAdapter(mContext, reqSize); mGridView = (GridView)findViewById(R.id.gridview); mGridView.setAdapter(adapter); }
@Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub int resId = 0; Log.d(TAG, "getView: position = " + position); if (convertView == null) { convertView = mInflater.inflate(R.layout.gridviewitem, null); } ImageView imageItem = (ImageView)convertView.findViewById(R.id.image_item); Log.d(TAG, "getView: type = " + mType); resId = GridViewConstData.getImageItemId(getFragmentType(), position); mLoader.loadImage(resId, imageItem); TextView textItem = (TextView)convertView.findViewById(R.id.text_item); textItem.setText(GridViewConstData.getItemTextId(getFragmentType(), position)); return convertView; }经测试发现,在执行findViewById会花比较久时间,这块用ViewHolder来优化。convertView是ListView的缓存,也可用来优化性能。
增加一个类ViewHolder,存储每个ListI tem或者Grid Item的组件内容,例如:
private class ViewHolder { ImageView mImageItem; TextView mTextItem; public ViewHolder(View layoutView) { mImageItem = (ImageView)layoutView.findViewById(R.id.image_item); mTextItem = (TextView)layoutView.findViewById(R.id.text_item); } }
getView函数改造如下:
@Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub int resId = 0; ViewHolder holder = null; Log.d(TAG, "getView: position = " + position); if (convertView == null || convertView.getTag() == null) { convertView = mInflater.inflate(R.layout.gridviewitem, null); holder = new ViewHolder(convertView); convertView.setTag(holder); } else { holder = (ViewHolder)convertView.getTag(); } resId = GridViewConstData.getImageItemId(getFragmentType(), position); mLoader.loadImage(resId, holder.mImageItem); holder.mTextItem.setText(GridViewConstData.getItemTextId(getFragmentType(), position)); return convertView; }