I\'m reading this tutorial http://android.amberfog.com/?p=296 . I\'d like to create a Listview weith different types of rows. I understand how to create the adapter, but wha
This might be a wrong method to do it. If you have only one component in the ListView then use simple adapter else use custom adapter with separate XML for the list row.
Sample code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listhistory);
initcomponents();
ArrayList> alist = new ArrayList>();
for (int i = 1; i < 20; i++) {
HashMap hmap = new HashMap();
hmap.put("date", "" + i + "/13");
hmap.put("restaurant", "Restaurant" + i);
hmap.put("distance", "" + (i * 100) + "kms");
alist.add(hmap);
}
final CustomListAdapter adapter = new CustomListAdapter(this,
R.layout.listitemhistory, alist);
list.setAdapter(adapter);
}
private void initcomponents() {
list = (ListView) findViewById(R.id.history_lst_list);
}
public void backButtonClick(View v) {
finish();
}
class CustomListAdapter extends ArrayAdapter> {
Context context;
int textViewResourceId;
ArrayList> alist;
public CustomListAdapter(Context context, int textViewResourceId,
ArrayList> alist) {
super(context, textViewResourceId);
this.context = context;
this.alist = alist;
this.textViewResourceId = textViewResourceId;
}
public int getCount() {
return alist.size();
}
public View getView(int pos, View convertView, ViewGroup parent) {
Holder holder = null;
LayoutInflater inflater = ((Activity) context)
.getLayoutInflater();
convertView = inflater.inflate(R.layout.listitemhistory,
parent, false);
holder = new Holder();
holder.date = (TextView) convertView
.findViewById(R.id.listitemhistory_txt_date);
holder.restaurant = (TextView) convertView
.findViewById(R.id.listitemhistory_txt_restaurant);
holder.distance = (TextView) convertView
.findViewById(R.id.listitemhistory_txt_distance);
holder.lin_background = (LinearLayout) convertView
.findViewById(R.id.history_lin_background);
convertView.setTag(holder);
holder = (Holder) convertView.getTag();
holder.date.setText(alist.get(pos).get("date"));
holder.restaurant.setText(alist.get(pos).get("restaurant"));
holder.distance.setText(alist.get(pos).get("distance"));
return convertView;
}
class Holder {
TextView date, restaurant, distance;
LinearLayout lin_background;
}
}