Android Adventures - Pickers |
Written by Mike James | |||||||
Thursday, 10 September 2015 | |||||||
Page 2 of 6
TimePicker In CodeTo interact with the TimePicker all you have to use is the get/set methods for Hour and Minute. You can also programatically change the 12 hour/24 hour mode. Notice that the time is always returned in 24-hour form no matter what the widget's mode is. There is also a problem with the latest API. Although the set/getCurrentMinute and set/getCurrentHour methods are deprecated the alternatives which do exactly the same thing set/getMinute and set/getHour don't work on earlier versions of Android (Icecream Sandwich in particular). So for the moment it seems preferable to use the deprecated methods and ignore the warnings. For example to set the TimePicker you would use
The only task remaining is figuring out how to discover then the user has selected a time. You could provide a button which the user has to click to confirm the new time. For example, if you place a Button and a TextView on the design surface, add the following Button click event handler:
and remember to set the Button's Click property to doButtonClick then you have a way for the user set the time.
In most cases the difficult part in using a Picker isn't setting it up or getting the data from it but in processing that data into a form that your program can use it in. In this case we simply convert the time into a slightly formatted string representation. Updating the time What about getting an update every time the user changes the TimePicker? The solution to this is to write an event handler for an OnTimeChanged event. As always, this is a matter of either implementing the OnTimeChangedListener Interface in the Activity or as an anonymous class. Using Android Studio the anonymous class is the simplest approach. If you type in
using the code completion then at the end Android Studio will generate a stub including the onTimeChanged method which you can add your code to:
You can guess that when the time is changed by the user the onTimeChanged method is called and the TimePicker that triggered the event is passed as view, and its hour and minute setting as hourOfDay and minute. All that remains is to set the event handler using the setOnTimeChangedListener method. For example, to transfer the new time to the TextView used in the previous example you would use:
And you need to add:
to OnCreate to associate the OnTimeChanged object and its event handling method with the TimePicker.
Now if you run the program you will see the TextView change every time the user alters the TimePicker by whatever method.
The full program, including the code for the button and the event handler is shown below and is also downloadable from the CodeBin:
|
|||||||
Last Updated ( Saturday, 15 October 2016 ) |