I want to implement a button that counts down when pressed. The idea is to allow the user to cancel the activation of the button. Once pressed, I would like for the button to change to red and read “CANCEL (3)” and countdown to “CANCEL (0)” and if it is pressed again, the countdown will stop and nothing will happen. If it is not canceled, the app will go to the next screen after time expires. Is there a way to update a button’s text each second (for the countdown) and change its functionality?
Thanks
You can use
postDelayedon a Handler to invoke your method later on the UI thread so that you can update the UI.There’s actually a very nice article about how this is done on Android already: http://developer.android.com/resources/articles/timed-ui-updates.html
You can get a Handler either by creating one in code running on the UI thread, or by calling
getHandler()on a view (e.g. your button itself).I’d provide an example, but the article linked already does so with great detail and clarity, so I’ll defer to it.
Edit: here’s a rough overview of how this will look. I don’t have the Android SDK installed right now, so I can’t verify that this works.
The timing may not be perfect (especially if there’s a lot of other CPU work going on), but it should be good enough for your purposes.