安卓原生自带的日期选择器DatePickerDialog、时间选择器TimePickerDialog使用方法
XML布局如下图:
![安卓原生自带的日期选择器DatePickerDialog、时间选择器TimePickerDialog使用方法_第1张图片](http://img.e-com-net.com/image/info8/9552d16e3417402ebefb302f5983be8a.jpg)
代码实现如下:
public class MainActivity extends AppCompatActivity {
private TextView timeShow;//定义一个TextView控件对象,显示得到的时间日期
private Button btn_date;
private Button btn_time;
DateFormat format = DateFormat.getDateTimeInstance();//获取日期格式器对象
Calendar calendar = Calendar.getInstance(Locale.CHINA);//获取日期格式器对象
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timeShow = ((TextView) findViewById(R.id.time));
btn_date = ((Button) findViewById(R.id.btn_date));//得到页面设定日期的按钮控件对象
btn_time = ((Button) findViewById(R.id.btn_time));
updateTimeShow(); //将页面TextView的显示更新为最新时间
btn_date.setOnClickListener(new View.OnClickListener() {//设置按钮的点击事件监听器
@Override
public void onClick(View v) {
//生成一个DatePickerDialog对象,并显示。显示的DatePickerDialog控件可以选择年月日,并设置
DatePickerDialog datePickerDialog = new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
//修改日历控件的年,月,日
//这里的year,monthOfYear,dayOfMonth的值与DatePickerDialog控件设置的最新值一致
calendar.set(Calendar.YEAR,year);
calendar.set(Calendar.MONTH,month);
calendar.set(Calendar.DAY_OF_MONTH,dayOfMonth);
updateTimeShow();
}
}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
datePickerDialog.show();
updateTimeShow(); //将页面TextView的显示更新为最新时间
}
});
btn_time.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TimePickerDialog timePickerDialog = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
//同DatePickerDialog控件
calendar.set(Calendar.HOUR_OF_DAY,hourOfDay);
calendar.set(Calendar.MINUTE,minute);
}
},calendar.get(Calendar.HOUR_OF_DAY),calendar.get(Calendar.MINUTE),true);
timePickerDialog.show();
updateTimeShow(); //将页面TextView的显示更新为最新时间
}
});
}
private void updateTimeShow(){ //将页面TextView的显示更新为最新时间
timeShow.setText(format.format(calendar.getTime()));
}
}
效果如下:
/![安卓原生自带的日期选择器DatePickerDialog、时间选择器TimePickerDialog使用方法_第3张图片](http://img.e-com-net.com/image/info8/4a7142b644f5409bbfe69897d82d28f6.jpg)