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:

 <?xml​version=”1.0”​encoding=”utf-8”?> 

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

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

package​ com.emergingandroidtech.TimePicker;
import ​android.app.Activity;
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)​{ 
​​​​​​​​super.onCreate(savedInstanceState); 
​​​​​​​​setContentView(R.layout.main);
​​​​​​​​timePicker = (TimePicker) findViewById(R.id.timePicker); 
​​​​​​​​timePicker.setIs24HourView(true);
​​​​​​​​
//---Button view--- ​​​​
​​​​Button btnOpen = (Button) findViewById(R.id.btnSet); ​
​​​​​​​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