DatePickerDialog和trimepickerDialog
设置时间对话框和日期对话框
public class MainActivity extends Activity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pickerdialog);
Button datebt = findViewById(R.id.datebt);
Button timebt = findViewById(R.id.timebt);
//为设置日期按钮绑定监听器
datebt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar ca = Calendar.getInstance();
//創建一个DatePickerDialog对话框实例,并将他显示出来 //绑定监听器
new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
EditText show = findViewById(R.id.show);
show.setText(“您选择了:” + year + “年” + (month + 1) + “月” + dayOfMonth + “日”);
}
}
//设置初始日期
, ca.get(Calendar.YEAR),
ca.get(Calendar.MONTH),
ca.get(Calendar.DAY_OF_MONTH)).show();
}
});
//为设置时间按钮设置监听器
timebt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar ca1 = Calendar.getInstance();
//創建一个TimePickerDialog实例并把它显示出来
new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
EditText et = findViewById(R.id.show);
et.setText("您选择了:" + hourOfDay + "时" + minute + "分");
}
}
//设置初始时间
, ca1.get(Calendar.HOUR_OF_DAY),
ca1.get(Calendar.MINUTE), true
//true采用24小时制
).show();
}
});
}
}
<?xml version="1.0" encoding="utf-8"?><EditText
android:id="@+id/show"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/datebt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="日期选择对话框" />
<Button
android:id="@+id/timebt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="时间选择对话框" />