搜尋此網誌

2014年10月23日 星期四

【Android】使用 ViewHolder Pattern改善Adapter效率

To improve performance, we should modify the custom adapter by applying the ViewHolder pattern which speeds up the population of the ListView considerably by caching view lookups for smoother, faster item loading:

public class UsersAdapter extends ArrayAdapter<User> {
// View lookup cache
private static class ViewHolder {
TextView name;
TextView home;
}
 
public UsersAdapter(Context context, ArrayList<User> users) {
super(context, R.layout.item_user, users);
}
 
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
User user = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.item_user, parent, false);
viewHolder.name = (TextView) convertView.findViewById(R.id.tvName);
viewHolder.home = (TextView) convertView.findViewById(R.id.tvHome);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// Populate the data into the template view using the data object
viewHolder.name.setText(user.name);
viewHolder.home.setText(user.hometown);
// Return the completed view to render on screen
return convertView;
}
}

沒有留言: