Override getView(): The Simple Way
Next, we need to use this layout ourselves in our RestaurantAdapter. To do this, we need to override getView() and inflate the layout as needed for rows.
Modify RestaurantAdapter to look like the following:
class RestaurantAdapter extends ArrayAdapter<Restaurant>
Modify RestaurantAdapter to look like the following:
class RestaurantAdapter extends ArrayAdapter<Restaurant>
{
RestaurantAdapter() {
super(LunchList.this,
android.R.layout.simple_list_item_1,
model);
}
public View getView(int position, View convertView,
ViewGroup parent) {
View row=convertView;
if (row==null) {
LayoutInflater inflater=getLayoutInflater();
row=inflater.inflate(R.layout.row, null);
}
Restaurant r=model.get(position);
((TextView)row.findViewById(R.id.title)).setText(r.getName());
((TextView)row.findViewById(R.id.address)).setText(r.getAddress());
ImageView icon=(ImageView)row.findViewById(R.id.icon);
if (r.getType().equals("sit_down")) {
icon.setImageResource(R.drawable.ball_red);
}
else if (r.getType().equals("take_out")) {
icon.setImageResource(R.drawable.ball_yellow);
}
else {
icon.setImageResource(R.drawable.ball_green);
}
return(row);
}
}
Notice how we create a row only if needed, recycling existing rows. But, we still pick out each TextView and ImageView from each row and populate it from the restaurant at the indicated position.
RestaurantAdapter() {
super(LunchList.this,
android.R.layout.simple_list_item_1,
model);
}
public View getView(int position, View convertView,
ViewGroup parent) {
View row=convertView;
if (row==null) {
LayoutInflater inflater=getLayoutInflater();
row=inflater.inflate(R.layout.row, null);
}
Restaurant r=model.get(position);
((TextView)row.findViewById(R.id.title)).setText(r.getName());
((TextView)row.findViewById(R.id.address)).setText(r.getAddress());
ImageView icon=(ImageView)row.findViewById(R.id.icon);
if (r.getType().equals("sit_down")) {
icon.setImageResource(R.drawable.ball_red);
}
else if (r.getType().equals("take_out")) {
icon.setImageResource(R.drawable.ball_yellow);
}
else {
icon.setImageResource(R.drawable.ball_green);
}
return(row);
}
}
Notice how we create a row only if needed, recycling existing rows. But, we still pick out each TextView and ImageView from each row and populate it from the restaurant at the indicated position.
No comments:
Post a Comment