转至:http://blog.csdn.net/dongshuai1991/article/details/8512628
版权声明:本文为博主原创文章,未经博主允许不得转载。
我用的是自定义dialog实现的,在DatePicker的onDateChangedListentr事件中实现范围的控制
代码如下:
- public class MainActivity extends Activity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- final TextView text = (TextView) findViewById(R.id.text);
- LayoutInflater l = LayoutInflater.from(this);
- View v = l.inflate(R.layout.dialog, null);
- final DatePicker datePicker = (DatePicker) v
- .findViewById(R.id.datepicker);
- datePicker.init(2000, 1, 3, new OnDateChangedListener() {
- @Override
- public void onDateChanged(DatePicker view, int year,
- int monthOfYear, int dayOfMonth) {
- if (isDateAfter(view)) {
- view.init(2000, 11, 30, this);
- }
- if (isDateBefore(view)) {
- view.init(1949, 11, 30, this);
- }
- }
- private boolean isDateAfter(DatePicker tempView) {
- if (tempView.getYear() > 2000) {
- return true;
- } else
- return false;
- }
- private boolean isDateBefore(DatePicker tempView) {
- if (tempView.getYear() < 1921) {
- return true;
- } else
- return false;
- }
- });
- Dialog dialog = new AlertDialog.Builder(this)
- .setTitle(
- datePicker.getYear() + "年"
- + (datePicker.getMonth() + 1) + "月"
- + datePicker.getDayOfMonth() + "日")
- .setView(v)
- .setIcon(R.drawable.ic_dialog_time)
- .setNeutralButton("设置", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- text.setText(datePicker.getYear() + "年"
- + (datePicker.getMonth() + 1) + "月"
- + datePicker.getDayOfMonth() + "日");
- }
- })
- .setNegativeButton("取消", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- dialog.cancel();
- }
- }).create();
- dialog.show();
- }
- }
自定义的dialog.xml代码如下
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
- <DatePicker
- android:id="@+id/datepicker"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content" />
- </LinearLayout>
以上在3.0版本之前支持,在3.0版本以后请使用下面的方法
- public void onClick(View v) {
- switch (answer.type) {
- case 1:// 日期类型
- DatePickerDialog dialog = new DatePickerDialog(ctx, this, 1980, 0,
- 1);
- DatePicker datePicker = dialog.getDatePicker();
- datePicker.setMinDate(DateUtils.getInstance().format("1970-01-01")
- .getTime());
- datePicker.setMaxDate(DateUtils.getInstance().format("2013-01-07")
- .getTime());
- dialog.show();
- break;
- }
- }
- @Override
- public void onDateSet(DatePicker view, int year, int monthOfYear,
- int dayOfMonth) {
- editText.setText(year + "年" + (monthOfYear + 1) + "月" + dayOfMonth
- + "日");
- }