DatePickerDialog.java 18.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
package com.fourmob.datetimepicker.date;

import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.SystemClock;
import android.os.Vibrator;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ectrip.trips.check.R;
import com.fourmob.datetimepicker.Utils;

public class DatePickerDialog extends DialogFragment implements
		View.OnClickListener, DatePickerController {

	private static final String KEY_SELECTED_YEAR = "year";
	private static final String KEY_SELECTED_MONTH = "month";
	private static final String KEY_SELECTED_DAY = "day";
	private static final String KEY_VIBRATE = "vibrate";

	// https://code.google.com/p/android/issues/detail?id=13050
	private static final int MAX_YEAR = 2037;
	private static final int MIN_YEAR = 1902;

	private static final int UNINITIALIZED = -1;
	private static final int MONTH_AND_DAY_VIEW = 0;
	private static final int YEAR_VIEW = 1;

	public static final int ANIMATION_DELAY = 500;
	public static final String KEY_WEEK_START = "week_start";
	public static final String KEY_YEAR_START = "year_start";
	public static final String KEY_YEAR_END = "year_end";
	public static final String KEY_CURRENT_VIEW = "current_view";
	public static final String KEY_LIST_POSITION = "list_position";
	public static final String KEY_LIST_POSITION_OFFSET = "list_position_offset";

	private static SimpleDateFormat DAY_FORMAT = new SimpleDateFormat("dd",
			Locale.getDefault());
	private static SimpleDateFormat YEAR_FORMAT = new SimpleDateFormat("yyyy",
			Locale.getDefault());
	private DateFormatSymbols mDateFormatSymbols = new DateFormatSymbols();

	private final Calendar mCalendar = Calendar.getInstance();
	private HashSet<OnDateChangedListener> mListeners = new HashSet<OnDateChangedListener>();
	private OnDateSetListener mCallBack;

	private AccessibleDateAnimator mAnimator;
	private boolean mDelayAnimation = true;
	private long mLastVibrate;
	private int mCurrentView = UNINITIALIZED;

	private int mWeekStart = mCalendar.getFirstDayOfWeek();
	private int mMaxYear = MAX_YEAR;
	private int mMinYear = MIN_YEAR;

	private String mDayPickerDescription;
	private String mYearPickerDescription;
	private String mSelectDay;
	private String mSelectYear;

	private TextView mDayOfWeekView;
	private DayPickerView mDayPickerView;
	private Button mDoneButton;
	private Button mCancelButton;
	private LinearLayout mMonthAndDayView;
	private TextView mSelectedDayTextView;
	private TextView mSelectedMonthTextView;
	private Vibrator mVibrator;
	private YearPickerView mYearPickerView;
	private TextView mYearView;
	private static boolean firstBtn;
	private static String dateStr;

	private boolean mVibrate = true;
	private boolean mCloseOnSingleTapDay;

	private void adjustDayInMonthIfNeeded(int month, int year) {
		int day = mCalendar.get(Calendar.DAY_OF_MONTH);
		int daysInMonth = Utils.getDaysInMonth(month, year);
		if (day > daysInMonth) {
			mCalendar.set(Calendar.DAY_OF_MONTH, daysInMonth);
		}
	}

	public DatePickerDialog() {
		// Empty constructor required for dialog fragment. DO NOT REMOVE
	}

	public static DatePickerDialog newInstance(
			OnDateSetListener onDateSetListener, int year, int month, int day,
			boolean first, String date) {
		return newInstance(onDateSetListener, year, month, day, true);
	}

	public static DatePickerDialog newInstance(
			OnDateSetListener onDateSetListener, int year, int month, int day,
			boolean vibrate) {
		DatePickerDialog datePickerDialog = new DatePickerDialog();
		datePickerDialog.initialize(onDateSetListener, year, month, day,
				vibrate);
		return datePickerDialog;
	}

	public void setVibrate(boolean vibrate) {
		mVibrate = vibrate;
	}

	private void setCurrentView(int currentView) {
		setCurrentView(currentView, false);
	}

	private void setCurrentView(int currentView, boolean forceRefresh) {
		long timeInMillis = mCalendar.getTimeInMillis();
		switch (currentView) {
		case MONTH_AND_DAY_VIEW:
			ObjectAnimator monthDayAnim = Utils.getPulseAnimator(
					mMonthAndDayView, 0.9F, 1.05F);
			if (mDelayAnimation) {
				monthDayAnim.setStartDelay(ANIMATION_DELAY);
				mDelayAnimation = false;
			}
			mDayPickerView.onDateChanged();
			if (mCurrentView != currentView || forceRefresh) {
				mMonthAndDayView.setSelected(true);
				mYearView.setSelected(false);
				mAnimator.setDisplayedChild(MONTH_AND_DAY_VIEW);
				mCurrentView = currentView;
			}
			monthDayAnim.start();
			String monthDayDesc = DateUtils.formatDateTime(getActivity(),
					timeInMillis, DateUtils.FORMAT_SHOW_DATE);
			mAnimator.setContentDescription(mDayPickerDescription + ": "
					+ monthDayDesc);
			Utils.tryAccessibilityAnnounce(mAnimator, mSelectDay);
			break;
		case YEAR_VIEW:
			ObjectAnimator yearAnim = Utils.getPulseAnimator(mYearView, 0.85F,
					1.1F);
			if (mDelayAnimation) {
				yearAnim.setStartDelay(ANIMATION_DELAY);
				mDelayAnimation = false;
			}
			mYearPickerView.onDateChanged();
			if (mCurrentView != currentView || forceRefresh) {
				mMonthAndDayView.setSelected(false);
				mYearView.setSelected(true);
				mAnimator.setDisplayedChild(YEAR_VIEW);
				mCurrentView = currentView;
			}
			yearAnim.start();
			String dayDesc = YEAR_FORMAT.format(timeInMillis);
			mAnimator.setContentDescription(mYearPickerDescription + ": "
					+ dayDesc);
			Utils.tryAccessibilityAnnounce(mAnimator, mSelectYear);
			break;
		}
	}

	private void updateDisplay(boolean announce) {
		/*
		 * if (mDayOfWeekView != null) {
		 * mDayOfWeekView.setText(mCalendar.getDisplayName(Calendar.DAY_OF_WEEK,
		 * Calendar.LONG,
		 * Locale.getDefault()).toUpperCase(Locale.getDefault())); }
		 * 
		 * mSelectedMonthTextView.setText(mCalendar.getDisplayName(Calendar.MONTH
		 * , Calendar.SHORT,
		 * Locale.getDefault()).toUpperCase(Locale.getDefault()));
		 */

		if (this.mDayOfWeekView != null) {
			this.mCalendar.setFirstDayOfWeek(mWeekStart);
			this.mDayOfWeekView
					.setText(mDateFormatSymbols.getWeekdays()[this.mCalendar
							.get(Calendar.DAY_OF_WEEK)].toUpperCase(Locale
							.getDefault()));
		}

		this.mSelectedMonthTextView
				.setText(mDateFormatSymbols.getMonths()[this.mCalendar
						.get(Calendar.MONTH)].toUpperCase(Locale.getDefault()));

		mSelectedDayTextView.setText(DAY_FORMAT.format(mCalendar.getTime()));
		mYearView.setText(YEAR_FORMAT.format(mCalendar.getTime()));

		// Accessibility.
		long millis = mCalendar.getTimeInMillis();
		mAnimator.setDateMillis(millis);
		int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_YEAR;
		String monthAndDayText = DateUtils.formatDateTime(getActivity(),
				millis, flags);
		mMonthAndDayView.setContentDescription(monthAndDayText);

		if (announce) {
			flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR;
			String fullDateText = DateUtils.formatDateTime(getActivity(),
					millis, flags);
			Utils.tryAccessibilityAnnounce(mAnimator, fullDateText);
		}
	}

	private void updatePickers() {
		Iterator<OnDateChangedListener> iterator = mListeners.iterator();
		while (iterator.hasNext()) {
			iterator.next().onDateChanged();
		}
	}

	public int getFirstDayOfWeek() {
		return mWeekStart;
	}

	public int getMaxYear() {
		return mMaxYear;
	}

	public int getMinYear() {
		return mMinYear;
	}

	public SimpleMonthAdapter.CalendarDay getSelectedDay() {
		return new SimpleMonthAdapter.CalendarDay(mCalendar);
	}

	public void initialize(OnDateSetListener onDateSetListener, int year,
			int month, int day, boolean vibrate) {
		if (year > MAX_YEAR)
			throw new IllegalArgumentException("year end must < " + MAX_YEAR);
		if (year < MIN_YEAR)
			throw new IllegalArgumentException("year end must > " + MIN_YEAR);
		mCallBack = onDateSetListener;
		mCalendar.set(Calendar.YEAR, year);
		mCalendar.set(Calendar.MONTH, month);
		mCalendar.set(Calendar.DAY_OF_MONTH, day);
		mVibrate = vibrate;
	}

	public void onClick(View view) {
		tryVibrate();
		if (view.getId() == R.id.date_picker_year)
			setCurrentView(YEAR_VIEW);
		else if (view.getId() == R.id.date_picker_month_and_day)
			setCurrentView(MONTH_AND_DAY_VIEW);
	}

	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		Activity activity = getActivity();
		activity.getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		mVibrator = ((Vibrator) activity.getSystemService("vibrator"));
		if (bundle != null) {
			mCalendar.set(Calendar.YEAR, bundle.getInt(KEY_SELECTED_YEAR));
			mCalendar.set(Calendar.MONTH, bundle.getInt(KEY_SELECTED_MONTH));
			mCalendar.set(Calendar.DAY_OF_MONTH,
					bundle.getInt(KEY_SELECTED_DAY));
			mVibrate = bundle.getBoolean(KEY_VIBRATE);
		}
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
	}

	@SuppressLint("InflateParams") 
	public View onCreateView(LayoutInflater layoutInflater, ViewGroup parent,
			Bundle bundle) {
		getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);

		View view = layoutInflater.inflate(R.layout.date_picker_dialog, null);

		mDayOfWeekView = ((TextView) view.findViewById(R.id.date_picker_header));
		mMonthAndDayView = ((LinearLayout) view
				.findViewById(R.id.date_picker_month_and_day));
		mMonthAndDayView.setOnClickListener(this);
		mSelectedMonthTextView = ((TextView) view
				.findViewById(R.id.date_picker_month));
		mSelectedDayTextView = ((TextView) view
				.findViewById(R.id.date_picker_day));
		mYearView = ((TextView) view.findViewById(R.id.date_picker_year));
		mYearView.setOnClickListener(this);

		int listPosition = -1;
		int currentView = MONTH_AND_DAY_VIEW;
		int listPositionOffset = 0;
		if (bundle != null) {
			mWeekStart = bundle.getInt(KEY_WEEK_START);
			mMinYear = bundle.getInt(KEY_YEAR_START);
			mMaxYear = bundle.getInt(KEY_YEAR_END);
			currentView = bundle.getInt(KEY_CURRENT_VIEW);
			listPosition = bundle.getInt(KEY_LIST_POSITION);
			listPositionOffset = bundle.getInt(KEY_LIST_POSITION_OFFSET);
		}

		Activity activity = getActivity();
		mDayPickerView = new DayPickerView(activity, this);
		mYearPickerView = new YearPickerView(activity, this);

		Resources resources = getResources();
		mDayPickerDescription = resources
				.getString(R.string.day_picker_description);
		mSelectDay = resources.getString(R.string.select_day);
		mYearPickerDescription = resources
				.getString(R.string.year_picker_description);
		mSelectYear = resources.getString(R.string.select_year);

		mAnimator = ((AccessibleDateAnimator) view.findViewById(R.id.animator));
		mAnimator.addView(mDayPickerView);
		mAnimator.addView(mYearPickerView);
		mAnimator.setDateMillis(mCalendar.getTimeInMillis());

		AlphaAnimation inAlphaAnimation = new AlphaAnimation(0.0F, 1.0F);
		inAlphaAnimation.setDuration(300L);
		mAnimator.setInAnimation(inAlphaAnimation);

		AlphaAnimation outAlphaAnimation = new AlphaAnimation(1.0F, 0.0F);
		outAlphaAnimation.setDuration(300L);
		mAnimator.setOutAnimation(outAlphaAnimation);

		mCancelButton = (Button) view.findViewById(R.id.cancle);
		mCancelButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dismiss();
			}
		});
		mDoneButton = ((Button) view.findViewById(R.id.done));
		mDoneButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				onDoneButtonClick();
			}
		});

		updateDisplay(false);
		setCurrentView(currentView, true);

		if (listPosition != -1) {
			if (currentView == MONTH_AND_DAY_VIEW) {
				mDayPickerView.postSetSelection(listPosition);
			}
			if (currentView == YEAR_VIEW) {
				mYearPickerView.postSetSelectionFromTop(listPosition,
						listPositionOffset);
			}
		}
		return view;
	}

	public void show(FragmentManager manager, String tag, boolean first,
			CharSequence date) {
		firstBtn = first;
		dateStr = (String) date;
		super.show(manager, tag);
	}

	public void setStartTime(String startTime) {
		dateStr = startTime;
	}

	public void setStartTime(CharSequence startTime) {
		if (startTime != null) {
			dateStr = (String) startTime;
		}
	}

	public void show(FragmentManager manager, String tag, boolean first,
			String date) {
		firstBtn = first;
		dateStr = date;
		super.show(manager, tag);
	}

	@SuppressLint("SimpleDateFormat")
	private void onDoneButtonClick() {
		Date current = new Date();
		try {
			if (daysBetween(current, mCalendar.getTime()) > 0) {
				mCallBack.onFail(getActivity().getString(
						R.string.not_choose_the_time_after_today));
				return;
			}
		} catch (ParseException e1) {
			e1.printStackTrace();
		}

		if (dateStr == null || dateStr.equals("")) {
			onData();
		} else {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date date = null;
			try {
				date = sdf.parse(dateStr);// 初始日期
			} catch (Exception e) {
				e.printStackTrace();
			}

			if (firstBtn) {
				int difference;
				try {
					difference = daysBetween(date, mCalendar.getTime());
					// if(difference>=-31){
					if (difference <= 0) {
						onData();
					} else {
						mCallBack
								.onFail(getActivity()
										.getString(
												R.string.The_former_time_can_not_be_greater_than_the_latter));
					}
					// }else{
					// mCallBack.onFail("两个日期距离不能超过31天!");
					// }
				} catch (ParseException e) {
					e.printStackTrace();
				}
			} else {
				int difference;
				try {
					difference = daysBetween(date, mCalendar.getTime());
					if (difference <= 31) {
						if (difference >= 0) {
							onData();
						} else {
							mCallBack
									.onFail(getActivity()
											.getString(
													R.string.The_latter_time_can_not_be_before_the_former));
						}
					} else {
						mCallBack.onFail(getActivity()
								.getString(
										R.string.Two_dates_can_not_be_more_than_31_days));
					}
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@SuppressLint("SimpleDateFormat") 
	private void onData() {
		tryVibrate();
		if (mCallBack != null) {
			String str = (new SimpleDateFormat("yyyy-MM-dd")).format(mCalendar
					.getTime());
			if (firstBtn) {
				// mCallBack.onDateSet(this, mCalendar.get(Calendar.YEAR),
				// mCalendar.get(Calendar.MONTH),
				// mCalendar.get(Calendar.DAY_OF_MONTH), true);
				mCallBack.onDateSet(this, str, true);
			} else {
				mCallBack.onDateSet(this, str, false);
			}
		}
		dismiss();
	}

	@SuppressLint("SimpleDateFormat")
	public static int daysBetween(Date smdate, Date bdate)
			throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		smdate = sdf.parse(sdf.format(smdate));
		bdate = sdf.parse(sdf.format(bdate));
		Calendar cal = Calendar.getInstance();
		cal.setTime(smdate);
		long time1 = cal.getTimeInMillis();
		cal.setTime(bdate);
		long time2 = cal.getTimeInMillis();
		long between_days = (time2 - time1) / (1000 * 3600 * 24);

		return Integer.parseInt(String.valueOf(between_days));
	}

	public void onDayOfMonthSelected(int year, int month, int day) {
		mCalendar.set(Calendar.YEAR, year);
		mCalendar.set(Calendar.MONTH, month);
		mCalendar.set(Calendar.DAY_OF_MONTH, day);
		updatePickers();
		updateDisplay(true);

		if (mCloseOnSingleTapDay) {
			onDoneButtonClick();
		}
	}

	public void onSaveInstanceState(Bundle bundle) {
		super.onSaveInstanceState(bundle);
		bundle.putInt(KEY_SELECTED_YEAR, mCalendar.get(Calendar.YEAR));
		bundle.putInt(KEY_SELECTED_MONTH, mCalendar.get(Calendar.MONTH));
		bundle.putInt(KEY_SELECTED_DAY, mCalendar.get(Calendar.DAY_OF_MONTH));
		bundle.putInt(KEY_WEEK_START, mWeekStart);
		bundle.putInt(KEY_YEAR_START, mMinYear);
		bundle.putInt(KEY_YEAR_END, mMaxYear);
		bundle.putInt(KEY_CURRENT_VIEW, mCurrentView);

		int listPosition = -1;
		if (mCurrentView == 0) {
			listPosition = mDayPickerView.getMostVisiblePosition();
		}
		if (mCurrentView == 1) {
			listPosition = mYearPickerView.getFirstVisiblePosition();
			bundle.putInt(KEY_LIST_POSITION_OFFSET,
					mYearPickerView.getFirstPositionOffset());
		}
		bundle.putInt(KEY_LIST_POSITION, listPosition);
		bundle.putBoolean(KEY_VIBRATE, mVibrate);
	}

	public void onYearSelected(int year) {
		adjustDayInMonthIfNeeded(mCalendar.get(Calendar.MONTH), year);
		mCalendar.set(Calendar.YEAR, year);
		updatePickers();
		setCurrentView(MONTH_AND_DAY_VIEW);
		updateDisplay(true);
	}

	public void registerOnDateChangedListener(
			OnDateChangedListener onDateChangedListener) {
		mListeners.add(onDateChangedListener);
	}

	public void setFirstDayOfWeek(int startOfWeek) {
		if (startOfWeek < Calendar.SUNDAY || startOfWeek > Calendar.SATURDAY) {
			throw new IllegalArgumentException(
					"Value must be between Calendar.SUNDAY and "
							+ "Calendar.SATURDAY");
		}
		mWeekStart = startOfWeek;
		if (mDayPickerView != null) {
			mDayPickerView.onChange();
		}
	}

	public void setOnDateSetListener(OnDateSetListener onDateSetListener) {
		mCallBack = onDateSetListener;
	}

	public void setYearRange(int minYear, int maxYear) {
		if (maxYear < minYear)
			throw new IllegalArgumentException(
					"Year end must be larger than year start");
		if (maxYear > MAX_YEAR)
			throw new IllegalArgumentException("max year end must < "
					+ MAX_YEAR);
		if (minYear < MIN_YEAR)
			throw new IllegalArgumentException("min year end must > "
					+ MIN_YEAR);
		mMinYear = minYear;
		mMaxYear = maxYear;
		if (mDayPickerView != null)
			mDayPickerView.onChange();
	}

	public void tryVibrate() {
		if (mVibrator != null && mVibrate) {
			long timeInMillis = SystemClock.uptimeMillis();
			if (timeInMillis - mLastVibrate >= 125L) {
				mVibrator.vibrate(5L);
				mLastVibrate = timeInMillis;
			}
		}
	}

	public void setCloseOnSingleTapDay(boolean closeOnSingleTapDay) {
		mCloseOnSingleTapDay = closeOnSingleTapDay;
	}

	static abstract interface OnDateChangedListener {
		public abstract void onDateChanged();
	}

	public static abstract interface OnDateSetListener {
		public abstract void onDateSet(DatePickerDialog datePickerDialog,
				String date, boolean firstBtn);

		public void onFail(String error);
	}
}