views:

200

answers:

1

In one of my Activities I have a ListView that displays a list of locations. For each list item I want a little arrow icon that points in the direction of the corresponding location. I implemented this icon by extending ImageView. This custom View has a listener that reacts to changes of the device's orientation by rotating the icon image accordingly. I register the listener in the onAttachedToWindow() method and unregister it in onDetachedFromWindow(). This kind of works but the problem is that onDetachedFromWindow() sometimes gets called only a long time after the containing Activity has paused. Also, the whole layout overall seems a little hacky. So my question is: Is there a proper way to unregister the listeners or would you implement this in a completely different way to begin with?

+1  A: 

I think you're having difficulty because your design is hacky like you acknowledge. I think what you should probably do is have your Activity listen for the device orientation and use onPause/onResume to handle the registering for orientation changes. Then have a custom cursor that is updated by the Activity when it changes. The custom cursor then can call notifyDataSetChanged to tell the ListView to update. Then in the getView call you can pass in the data necessary for your arrow to display correctly. This way the only arrows that will be updated are those that are visible. You'll only have one place where you are receiving orientation data and later you can handle the onScrollStateChanged and stop updating the arrows when the user is scrolling if it impacts the scroll animations too much.

Qberticus
Thanks a lot! Listening for the orientation in the Activity really seems to be the right thing to do here since there is no need to do that in more than one place and the Activity is also the only place where I can use onPause and onStart. However, I started implementing it this way and discovered a new problem: calling notifyDataSetChanged with such a high frequency is even heavier on performance because getView will also update everything else about the list items. There would have to be a way to make sure that only the icons are affected by these updates. What do I do now?
legr3c