Reputation: 2881
I know how to access a listview item through an onitemclicklistener but how do I do something like change the background color in code.
sudo code:
lv[0].setBackgroundResource(R.color.red); //change the background of the first listview item
Is there a way to access each view of the listview?
Upvotes: 1
Views: 2703
Reputation: 134664
@Matt: It's not that it's weak, you just have to understand the way it works.
Yellavon, at any given time, your ListView only contains the visible items, so you can't access and change items directly. As they scroll out of view, the views are recycled, and populated with data by the ListAdapter. It's within this adapter that you need to handle the cases where items should differ. If you've created your own custom ListAdapter (e.g. ArrayAdapter, BaseAdapter), in your getView()
method, simply add some logic within to handle the cases in which the background color should change.
Let's say for example, you have a list of integers, and you want any integer >= 50 to show up in red:
if(items.get(position) >= 50) {
myView.setBackgroundColor("#FF0000");
} else {
myView.setBackgroundColor("#000000");
}
(It's important to make sure to handle the else cases, as you may get a recycled view of an item that had been colored red. In this case, you'd have to reset it to whatever default background color you need.)
If you've never built a custom adapter, this excerpt from CommonsWare's book on creating custom ListAdapters is a great resource.
EDIT: Further thought, based on your comment:
In your custom ExpandableListAdapter
private Object lastSelectedObject;
public void setLastSelectedObject(Object obj) {
lastSelectedObject = obj;
}
public Object getLastSelectedObject() {
return lastSelectedObject;
}
Implement onListItemClick(ListView l, View v, int pos, long id)
in your ListActivity
@Override
protected void onListItemClick(ListView l, View v, int pos, long id) {
super.onListItemClick(l, v, pos, id);
((CustomAdapter)l.getAdapter()).setLastSelectedObject(items.get(pos));
}
Now, back in getView()
Object obj = getLastSelectedObject();
if(obj != null) {
//handle background switching for your View here
} else {
//reset background to default for recycled views
}
Upvotes: 2
Reputation: 5212
Have a look at this example
int first = view.getFirstVisiblePosition();
int count = view.getChildCount();
for (int i=0; i<count; i++) {
TextView t = (TextView)view.getChildAt(i);
if (t.getTag() != null) {
t.setText(mStrings[first + i]);
t.setTag(null);
}
}
Seems like getChildAt is the method you are looking for.
Upvotes: 0
Reputation: 5511
The ListView class in android is weak.
The short answer to your question is no, not easily.
Someone asked about it at the Google I/O and the answer from the android team was to use a vertically filling LinearLayout and just add a stack of child views into it (which basically gives it the same functionality as a ListView).
You can do getChild(x) to get any of the views
Upvotes: -1