日期:
xml:
<Button android:id="@+id/addtime" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="日期选择器" />
java:
private Button btnChooseDate; btnChooseDate = findViewById(R.id.addtime); btnChooseDate.setOnClickListener(new View.OnClickListener() { /** * 当然并不是所有静态context都是可以用来创建dialog的,例如***App().getApplication().getApplicationContext()这个context就不行,因为它并不代表哪一个Activity或者View。。这样就无法add这个dialog。 * @param v */ @Override public void onClick(View v) { new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { Log.d(TAG, String.format("%d-%d-%d", year, month, dayOfMonth)); String theDate = String.format("%d-%d-%d", year, month, dayOfMonth); btnChooseDate.setText(theDate); } }, 2019, 1, 22).show(); } });
时间:
xml:
<Button android:id="@+id/addtime" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="时间选择器" />
java:
private Button btnChooseTime;
btnChooseTime = findViewById(R.id.addtime); btnChooseTime.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { Log.d(TAG, String.format("%d:%d", hourOfDay, minute)); String theTime = String.format("%d:%d", hourOfDay, minute); btnChooseTime.setText(theTime); } }, 0, 0, true).show(); } });