1.创建dialog 布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<DatePicker
android:datePickerMode="spinner"
android:calendarViewShown="false"
android:id="@+id/date_picker"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</DatePicker>
</LinearLayout>
2.MainActivity
public class MainActivity extends AppCompatActivity {
private TextView date;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
date = findViewById(R.id.date);
//点击"日期"按钮布局 设置日期
date.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//通过自定义控件AlertDialog实现
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
View view = (LinearLayout) getLayoutInflater().inflate(R.layout.date_dialog, null);
final DatePicker datePicker = (DatePicker) view.findViewById(R.id.date_picker);
//设置日期简略显示 否则详细显示 包括:星期\周
datePicker.setCalendarViewShown(false);
//设置date布局
builder.setView(view);
builder.setTitle("选择出生日期");
builder.setPositiveButton("确 定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//日期格式
int year = datePicker.getYear();
int month = datePicker.getMonth()+1;
int dayOfMonth = datePicker.getDayOfMonth();
date.setText(year+"年"+month+"月"+dayOfMonth+"日");
dialog.cancel();
}
});
builder.setNegativeButton("取 消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.create().show();
}
});
}
}
3.activity_main布局
<?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"
tools:context=".MainActivity">
<TextView
android:id="@+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2020年06月01日"></TextView>
</LinearLayout>