天天看點

android日期篩選_安卓原生自帶的日期選擇器、時間選擇器使用方法

Activity的代碼實作如下:

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()));

}

}