Android Programming Tutorials

(Romina) #1
Making Our List Be Fancy

}

else if (r.getType().equals("take_out")) {
icon.setImageResource(R.drawable.ball_yellow);
}
else {
icon.setImageResource(R.drawable.ball_green);
}
}
}

Step #5: Recycle Rows via RestaurantHolder....................................


To take advantage of the new RestaurantHolder, we need to modify


getView() in RestaurantAdapter. Following the holder pattern, we need to


create a RestaurantHolder when we inflate a new row, cache that wrapper in


the row via setTag(), then get it back later via getTag().


Change getView() to look like the following:


class RestaurantAdapter extends ArrayAdapter<Restaurant> {
RestaurantAdapter() {
super(LunchList.this, R.layout.row, model);
}

public View getView(int position, View convertView,
ViewGroup parent) {
View row=convertView;
RestaurantHolder holder=null;

if (row==null) {
LayoutInflater inflater=getLayoutInflater();

row=inflater.inflate(R.layout.row, parent, false);
holder=new RestaurantHolder(row);
row.setTag(holder);
}
else {
holder=(RestaurantHolder)row.getTag();
}

holder.populateFrom(model.get(position));

return(row);
}
}

This means the whole LunchList class looks like:


42
Free download pdf