views:

37

answers:

2

Suppose I have a listview with 3 rows. If the user clicks a button in row 1, it expands a menu (it's just a linear layout that's shown/hidden). If they then click on an item in row 2, I'd like to be able to collapse the menu in row 1. Is this possible? If so, how?

+1  A: 

You can always use getContext() on the View to get a reference to the containing Activity, which you can cast to a ListActivity (assuming you're using that) and call the usual methods to get the data at that position in the ListAdapter:

((ListActivity) v.getContext()).getListAdapter().getItem(1) 

Then you can manipulate your data however you want to and call notifyDataSetChanged() on your ListAdapter.

But it'd probably be a lot easier for you and your users to just use ExpandableListView, which gives you expandable lists with predictable interactions your users already know. You can check the history activity in the Browser source code in AOSP for a real life example. And if it doesn't exactly meet your needs, you can always yank the code for ExpandableListView itself from the Android source.

Yoni Samlan
I wish it was that easy, unfortunately the expandable list view wont do what i need it to. Also, I'm not using the ListActivity. instead, i have a ListView that is inside a layout which is then rendered by a normal activity...
Ben
Well, you probably should just use ListActivity; it's just a light wrapper around a normal activity that keeps track of your ListView/ListAdapter for you fairly painlessly. But if you don't want to or can't for some reason, you can either keep a member variable reference to your ListView/Adapter in your Activity somewhere, or you can just do it this way (substitute your listview's ID for android.R.id.listview): `((ListActivity) v.getContext()).findViewById(android.R.id.listview).getAdapter().getItem(1)`etc.
Yoni Samlan
+1  A: 

Save a reference to the View you would like to manipulate later. Probably wrap in a final variable, then you will be easy to change.

Pentium10
NEVER EVER do this. Saving a refernce to a view in a listview will cause you major problems. The views get recycled internally as soon as they go off screen and trying to write to them will in the best case cause a crash.
CodeFusionMobile
yes, CSharperWithjava is right... that's a bad idea...
Ben
I say that because i tried it and its all buggy...
Ben
actually, i ended up getting this to work and its not that bad. i have to set the reference to null when they scroll, but it works because it will only ever affect the view that is visible.
Ben