views:

159

answers:

2

In my activity I respond to an onClick() by replacing the current view with a new one (setContentView()). For some reason when I do this and then go back to the original view later the button I originally pressed still looks like it is pressed.

If you 'refresh' it somehow (e.g. scroll over it with the trackball) then it reverts to the unpressed state. It's as if the button doesn't get the 'touch-up' event.

The weird thing is: This only happens on my T-Mobile Pulse (android 1.5). It doesn't happen on the emulator.

I've tried calling invalidate()/postInvalidate() on the view when I show it but it doesn't have any effect.

+1  A: 

Sounds like onClick() executes before the button's View gets set back to its unclicked state and since you remove the view before that happens, it maintains its clicked state. You could try something like requesting focus with another item during the onClick(). However, calling a setContentView() repeatedly on a screen sounds a little strange. Are you sure you shouldn't be using another Activity? That would fix your button state issue.

jqpubliq
+3  A: 

My guess is that your "touch-up" event will go to your new content view.

You can either:

  • Not call setContentView() at all in onClick(), using other means of achieving your UI aims (multiple activities, ViewFlipper, etc.).
  • Not call setContentView() immediately in onClick(), but instead post() a Runnable that will call setContentView(). That should put the content view replacement in the event queue after the "touch-up" event.

Personally, I am not a big fan of activities constantly calling setContentView(), as I worry about memory leaks and overly-plump activities making state and memory management more difficult. For example, let's say you call setContentView() for your original layout (A), then call setContentView() for your new layout (B), then the user rotates the screen. Android's default onSaveInstanceState() will help you with B -- hanging onto EditText contents and the like -- but for A, you're on your own.

CommonsWare
Ah, I didn't know about ViewFlipper (or ViewSwitcher!) Looks like exactly what I want. Example here for future readers: http://www.ctctlabs.com/index.php/blog/detail/android_dont_overlook_viewswitcher/
Timmmm