I am trying to think of a way how my adapter, based on parse data, could assign background images to buttons place in rows within a ListView. What my app does is downloads json data from a server. Then it is parsed and is used to load an adapter, which shows a list of to-do/done tasks. Next to every task is a button indicating whether it has/hasn’t been done. Any pointers much appreciated. Thank you.
Asked
Active
Viewed 736 times
1 Answers
1
Assuming that you know how to get and parse json data, create list view with a item layout with required text and image, use the following anomaly to create your custom adapter.
During creating each view in getView(...)
pass the images you want into the adapter run time.
Every time you refresh the adapter data, call adapter.notifyDataSetChanged();
public class MyAdapter extends ArrayAdapter<Item> {
private ArrayList<Item> items;
private ViewHolder Holder;
private class ViewHolder {
TextView title, cost;
Button delete;
}
public MyAdapter(Context context, int tvResId, ArrayList<Item> items) {
super(context, tvResId, items);
this.items = items;
}
@Override
public View getView(int pos, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.cost_estimate_list_item, null);
Holder = new ViewHolder();
Holder.title = (TextView) v.findViewById(R.id.tvCEListText);
Holder.cost = (TextView) v.findViewById(R.id.tvCEListPrice);
Holder.delete = (Button) v.findViewById(R.id.bCEListDelBtn);
v.setTag(Holder);
} else
Holder = (ViewHolder) v.getTag();
final Item item = items.get(pos);
if (item != null) {
Holder.title.setText(item.getTitle());
Holder.cost.setText("Rs." + item.getPrice());
}
Holder.delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
items.remove(item);
notifyDataSetChanged();
updateTotal();
}
});
return v;
}
}
class Item {
private String title, price;
public String getTitle() {
return title;
}
public String getPrice() {
return price;
}
public Item(String t, String p) {
title = t;
price = p;
}
}
Let me know if you still need help on this.

GrIsHu
- 29,068
- 10
- 64
- 102

Ravi Teja Vupasi
- 113
- 6
-
thanks a lot for your help, Ravs. I think I fully get how the above code works and I am trying to implement it. What I am struggling with is how to make it work with a SimpleAdapter, since I am not sure if existing constructors for ArrayAdapter can take all the arguments I am passing. Here is the code representing this part: ListAdapter adapter = new SimpleAdapter(this, myHabitsList, R.layout.my_habits_list_item, new String[] {TAG_TITLE, TAG_HABIT_ID}, new int[] {R.id.title, R.id.habit_id}); – Egis Mar 19 '13 at 11:06
-
You can always use global vars and create the adapter class inside the main class file. This way, you can avoid passing every var via args – Ravi Teja Vupasi Mar 25 '13 at 05:04