一、样式文件time.xml
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/datePicker"
android:layout_gravity="center_horizontal" />
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/timePicker"
android:layout_gravity="center_horizontal" />
二、activity文件:
package com.demo.yaokj.timedemo;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TimePicker;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private DatePicker datePicker;
private TimePicker timePicker;
private Calendar calendar;
private int year ;
private int month;
private int dayOfMonth;
private int hour;
private int min;
private int sec;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.time);
datePicker = (DatePicker) findViewById(R.id.datePicker);
timePicker = (TimePicker) findViewById(R.id.timePicker);
calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH) + 1;
dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH) ;
hour = calendar.get(Calendar.HOUR);
min = calendar.get(Calendar.MINUTE);
sec = calendar.get(Calendar.SECOND);
setTitle(year+"-"+month+"-"+dayOfMonth+" "+hour+":"+min+":"+sec);
//这里初始化
datePicker.init(year, month, dayOfMonth, new DatePicker.OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
setTitle(year+"-"+ (monthOfYear + 1) +"-"+dayOfMonth);
}
});
timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
setTitle(year+"-"+ (month + 1) +"-"+dayOfMonth + " "+hourOfDay+":"+minute );
}
});
new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
setTitle(year+"-"+ (monthOfYear + 1) +"-"+dayOfMonth);
}
},year,month,dayOfMonth).show();
new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
setTitle(year+"-"+ (month + 1) +"-"+dayOfMonth + " "+hourOfDay+":"+minute );
}
},hour,min,true).show();
}
}