菜鸟的Android学习之路11——时间日期拾取器

时间:2021-12-28 06:47:22

代码:

import java.util.Calendar;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.DatePicker;
import android.widget.TimePicker.OnTimeChangedListener;
import android.widget.Toast;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.TimePicker;

public class MainActivity extends Activity {
 private int year;
 private int month;
 private int day;
 private int hour;
 private int minute;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  //获取日期拾取组件
  DatePicker datepicker=(DatePicker)findViewById(R.id.datePicker1);
  TimePicker timepicker=(TimePicker)findViewById(R.id.timePicker1);
  timepicker.setIs24HourView(true);
  //创建一个日历对象,获取当前的时间
  Calendar calendar=Calendar.getInstance();
  year=calendar.get(Calendar.YEAR);
  month=calendar.get(Calendar.MONTH);
  day=calendar.get(Calendar.DAY_OF_MONTH);
  hour =calendar.get(Calendar.HOUR_OF_DAY);
  minute=calendar.get(Calendar.MINUTE);
  //set current hours
  timepicker.setCurrentHour(hour);
  timepicker.setCurrentMinute(minute);//set current minute
  //初始化日期拾取器,并初始化指定监听器
  datepicker.init(year, month, day, new OnDateChangedListener() {
   
   @Override
   public void onDateChanged(DatePicker view, int year, int monthOfYear,
     int dayOfMonth) {
    MainActivity.this.year=year;
    MainActivity.this.month=monthOfYear;
    MainActivity.this.day=dayOfMonth;
    show(year,month,day,hour,minute);
    // TODO Auto-generated method stub
   }  
  });
  //为时间拾取器设置监听器
  timepicker.setOnTimeChangedListener(new OnTimeChangedListener() {
   
   @Override
   public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
    MainActivity.this.hour=hourOfDay;
    MainActivity.this.minute=minute;
    show(year,month,day,hour,minute);// TODO Auto-generated method stub
    
   }
  });
  
 }
   private void show(int year, int month, int day, int hour, int minute) {
    // TODO Auto-generated method stub
    String str=year+"年"+month+"月"+day+"day"+hour+"hour"+":"+minute;
    Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
   }
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

}

效果如下:

菜鸟的Android学习之路11——时间日期拾取器