Android UI Tutorial - Android TimePicker








You use the TimePicker control to pick a time.

Example

The following xml layout defines a TimePicker.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/timeDefault"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <TimePicker
        android:id="@+id/timePicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

The following code sets TimePicker with Time.

package com.java2s.app;
/*from www .  jav a  2  s. c om*/
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.TimePicker;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView timeDefault = (TextView)findViewById(R.id.timeDefault);

        TimePicker tp = (TimePicker)this.findViewById(R.id.timePicker);

        java.util.Formatter timeF = new java.util.Formatter();
        timeF.format("Time defaulted to %d:%02d", tp.getCurrentHour(),
                tp.getCurrentMinute());
        timeDefault.setText(timeF.toString());

        tp.setIs24HourView(true);
        tp.setCurrentHour(new Integer(10));
        tp.setCurrentMinute(new Integer(10));
    }

}
null




Note

For the TimePicker, the number of hours and minutes is set to 10. TimePicker supports 24-hour view.

If you do not set values for these controls, the default values will be the current date and time as known to the device.