Saturday, 28 February 2015

Time Picker in Android

TimePicker View 

The TimePicker view enables users to select a time of the day, in either 24-hour mode or AM/PM mode.

Using the TimePicker View

1 . Modify the main.xml file located in the res/layout folder by adding the following lines in bold:


<LinearLayout​ xmlns:android=”” ​​​​android:orientation=”vertical” ​​​​
<TimePicker android:id=”@+id/timePicker” 
​​​​android:layout_width=”wrap_content” ​​
​​android:layout_height=”wrap_content” />
<Button android:id=”@+id/btnSet” 
​​​​android:text=”I am all set!” />

 2 . Add the following statements in bold to the file: 

package​ com.emergingandroidtech.TimePicker;
import ​;
import ​android.os.Bundle;
import android.view.View;
import android.widget.Button; 
import android.widget.TimePicker; 
import android.widget.Toast;
public ​class ​MainActivity ​extends ​Activity
​​​​TimePicker timePicker; ​
 ​​​​/**​Called ​when​ the​ activity​ is ​first​ created.​*/ 

​​​​@Override ​​​​public ​void ​onCreate(Bundle​savedInstanceState)​{ 
​​​​​​​​timePicker = (TimePicker) findViewById(; 
//---Button view--- ​​​​
​​​​Button btnOpen = (Button) findViewById(; ​
​​​​​​​btnOpen.setOnClickListener(new View.OnClickListener() {
​          public void onClick(View v) 
       ​​​​​​​​​​​​​​​​Toast.makeText(getBaseContext(), ​​​​​​​​​​​​​​​​​​​​​​​​“Time selected:” + ​​​​​​​​​​​​​​​​​​​​​​​​​​timePicker.getCurrentHour() + ​​​​​​​​​​​​​​​​​​​​​​​​“:” + timePicker.getCurrentMinute(), ​​​​​​​​​​​​​​​​​​​​​​​​Toast.LENGTH_SHORT).show(); ​
          ​​​​​​​​​​​} ​​​​​​​​
3 . This time, the TimePicker will be displayed in the 24-hour format. Clicking the Button will display the time that you have set in the TimePicker.

How It Works 

The TimePicker displays a standard UI to enable users to set a time. By default, it displays the time in the AM/PM format. If you wish to display the time in the 24-hour format, you can use the  setIs24Hour​View() method. 
To programmatically get the time set by the user, use the getCurrentHour() and getCurrentMinute() methods:
​​​​​​​​​​​​​​​​Toast.makeText(getBaseContext(), ​​​​​​​​​​​​​​​​​​​​​​​​“Time​selected:”​+ ​​​​​​​​​​​​​​​​​​​​​​​​​​timePicker.getCurrentHour() + ​​​​​​​​​​​​​​​​​​​​​​​​“:”​+​timePicker.getCurrentMinute(), ​​​​​​​​​​​​​​​​​​​​​​​​Toast.LENGTH_SHORT).show();

No comments:

Post a Comment