public class MainActivity extends Activity { private DatePicker date_picker;private TimePicker time_picker;private TextView tv_date;private TextView t ...
public class MainActivity extends Activity {
private DatePicker date_picker;
private TimePicker time_picker;
private TextView tv_date;
private TextView tv_time;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//初始化
date_picker=(DatePicker) findViewById(R.id.date);
time_picker=(TimePicker) findViewById(R.id.time);
tv_date=(TextView) findViewById(R.id.tv_date);
tv_time=(TextView) findViewById(R.id.tv_time);
//獲取當前的年月日時分信息
Calendar c=Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month=c.get(Calendar.MONTH);
int day=c.get(Calendar.DAY_OF_MONTH);
int hour=c.get(Calendar.HOUR_OF_DAY);
int minute=c.get(Calendar.MINUTE);
//使用Calendar顯示時,月份從0開始,顯示的時候加1
tv_date.setText("現在日期:"+year+"-"+(month+1)+"-"+day);
tv_time.setText("現在時間:"+hour+":"+minute);
//初始化日期時候,需要日期監聽器
date_picker.init(year, month, day, new OnDateChangedListener() ;{
//監聽日期的改變
public void onDateChanged(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
//Toast.makeText(MainActivity.this, "現在時間:"+year+"-"+(monthOfYear+1)+"-"+dayOfMonth, 0).show();
//月份以0開始統計,顯示的時候要加1
tv_date.setText("現在日期:"+year+"-"+(monthOfYear+1)+"-"+dayOfMonth);
}
});
//設置時間為24小時制
time_picker.setIs24HourView(true);
//時間監聽器
time_picker.setOnTimeChangedListener(new OnTimeChangedListener() {
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
// TODO Auto-generated method stub
tv_time.setText("現在時間:"+hourOfDay+":"+minute);
}
});