一、前言:这篇文章是关于DatePickerDialog,点击按钮出现一个日期选择器对话框,通过点击确认把选则的日期显示到文本控件上。
二、上代码
页面布局xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".picker.DatePickerActivity">
<Button
android:id="@+id/btn_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="请选择日期"/>
<DatePicker
android:id="@+id/dp_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:calendarViewShown="false"
android:datePickerMode="spinner"/>
<Button
android:id="@+id/btn_ok"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="确定"/>
<TextView
android:id="@+id/tv_date"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
对应的Activity:DatePickerActivity
public class DatePickerActivity extends AppCompatActivity implements View.OnClickListener, DatePickerDialog.OnDateSetListener {
private DatePicker dp_date;
private TextView tv_result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_date_picker);
findViewById(R.id.btn_ok).setOnClickListener(this);
findViewById(R.id.btn_date).setOnClickListener(this);
tv_result = findViewById(R.id.tv_date);
dp_date = findViewById(R.id.dp_date);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_ok:
String desc = String.format("您选择的日期是:%d年%d月%d月",dp_date.getYear(),dp_date.getMonth()+1,dp_date.getDayOfMonth());
tv_result.setText(desc);
break;
case R.id.btn_date:
// //获取日历的一个实例。里面包含了当前的年月日
// Calendar calendar = Calendar.getInstance();
// calendar.get(Calendar.YEAR);
// calendar.get(Calendar.MONTH);
// calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(this,this,2023,5,11);
//显示对话框
datePickerDialog.show();
break;
}
}
@Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
String desc = String.format("您选择的日期是:%d年%d月%d月",i,i1+1,i2);
tv_result.setText(desc);
}
}
运行结果展示: