Wednesday, September 28, 2011

Android Time Picker Dialog Example

In Android, we can display Time Picker in the dialog box itself.
Here is an example to show how to display the time picker in the dialog box in order to get the time.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/Button01" android:text="time"/>
</LinearLayout>
public class ExampleApp extends Activity {

    private Button b1;
    static final int TIME_DIALOG_ID = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        b1 = (Button) findViewById(R.id.Button01);
        b1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(TIME_DIALOG_ID);
            }
        });
    }
    private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            Toast.makeText(ExampleApp.this, "Time is="+hourOfDay+":"+minute, Toast.LENGTH_SHORT).show();
        }
    };
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case TIME_DIALOG_ID:
                return new TimePickerDialog(this,mTimeSetListener, 0, 0, false);
        }
        return null;
    }
}
The output will look like

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.