Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Android-ListView的优化(二) #5

Open
jeffrey1995 opened this issue Jun 13, 2016 · 0 comments
Open

Android-ListView的优化(二) #5

jeffrey1995 opened this issue Jun 13, 2016 · 0 comments

Comments

@jeffrey1995
Copy link
Owner

简单谈一下ListView的优化问题,简单主要分为两个方面:
这里我用上一章的工程作为例子。

1. 布局缓存。

Adapter里的getView()方法中海油一个convertView参数,这个参数用于将之前加载好的布局进行缓存,以便之后可以进行重用。
修改FruitAdapter中的代码:
@OverRide
public View getView(int position, View convertView, ViewGroup parent) {
Fruit fruit = getItem(position);
View view;
if(convertView == null)
{
view = LayoutInflater.from(getContext()).inflate(resourceId, null);
}
else
{
view = convertView;
}
ImageView fruitImage = (ImageView) view.findViewById(R.id.fruit_image);
TextView fruitName = (TextView) view.findViewById(R.id.fruit_name);
fruitImage.setImageResource(fruit.getImageId());
fruitName.setText(fruit.getName());
return view;
}
如果convertView为空,则用LayoutInflater去加载布局,如果convertView不为空,则直接对convertView进行重用。这样很大的提高了运行效率。

2. 借助一个ViewHolder来对控件进行缓存,修改FruitAdapter的代码。

@OverRide
public View getView(int position, View convertView, ViewGroup parent) {
Fruit fruit = getItem(position);
View view;
ViewHolder viewHolder;
if(convertView == null)
{
view = LayoutInflater.from(getContext()).inflate(resourceId, null);
viewHolder = new ViewHolder();
viewHolder.fruitImage = (ImageView) view.findViewById(R.id.fruit_image);
viewHolder.fruitName = (TextView) view.findViewById(R.id.fruit_name);
view.setTag(viewHolder); //将viewholder存储在viwe中
}
else
{
view = convertView;
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.fruitImage.setImageResource(fruit.getImageId());
viewHolder.fruitName.setText(fruit.getName());
return view;
}
class ViewHolder
{
ImageView fruitImage;
TextView fruitName;
}
}
在adapter类中新建一个ViewHolder类来记录控件,在getView()方法中,只需要在第一次对ListView子项中的控件初始化(findViewById)将其保存在ViewHolder中,然后利用view的setTag将viewHoler对象保存起来,下一次可以利用getTag再次获取ViewHolder对象。
这样对控件进行缓存。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant