<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="TimeDialog" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/button1"
android:text="DateDialog" />
</RelativeLayout>
Code:
package com.cy.mypicker;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TimePicker;
public class MainActivity extends Activity {
Button btn_TimeDialog, btn_DateDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
btn_TimeDialog = (Button) findViewById(R.id.button1);
btn_DateDialog = (Button) findViewById(R.id.button2);
btn_TimeDialog.setOnClickListener(timeDialogOnClickListener);
btn_DateDialog.setOnClickListener(dateDialogOnClickListener);
}
OnClickListener timeDialogOnClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
TimePickerDialog dialog = new TimePickerDialog(MainActivity.this,
new OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
Boolean isAM = hourOfDay < 12 ? true : false;
String msg = isAM == true ? "AM" : "PM";
Log.i("time", msg + " " + hourOfDay + ":" + minute);
}
// false = 12, true = 24
}, 0, 0, false);
dialog.show();
}
};
OnClickListener dateDialogOnClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
DatePickerDialog datePickerDialog = new DatePickerDialog(
MainActivity.this, new OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
Log.i("date", year + ", " + monthOfYear + ", "
+ dayOfMonth + ", " + view.getMonth());
}
}, 2014, 3, 11);
datePickerDialog.show();
}
};
}
TimeDialog
DateDialog
Log
參考資料:
http://developer.android.com/guide/topics/ui/controls/pickers.html
http://developer.android.com/reference/android/app/TimePickerDialog.html
http://stackoverflow.com/questions/7527138/timepicker-how-to-get-am-or-pm


