97 lines
2.7 KiB
Java
97 lines
2.7 KiB
Java
package com.xscm.moduleutil.widget;
|
|
|
|
import android.content.Context;
|
|
import android.util.AttributeSet;
|
|
import android.widget.LinearLayout;
|
|
import android.widget.NumberPicker;
|
|
|
|
import java.util.Calendar;
|
|
|
|
public class WheelDatePicker extends LinearLayout {
|
|
|
|
private NumberPicker yearPicker, monthPicker, dayPicker;
|
|
private int maxDay = 31;
|
|
|
|
public WheelDatePicker(Context context) {
|
|
this(context, null);
|
|
}
|
|
|
|
public WheelDatePicker(Context context, AttributeSet attrs) {
|
|
super(context, attrs);
|
|
init(context);
|
|
}
|
|
|
|
private void init(Context context) {
|
|
setOrientation(HORIZONTAL);
|
|
|
|
yearPicker = new NumberPicker(context);
|
|
monthPicker = new NumberPicker(context);
|
|
dayPicker = new NumberPicker(context);
|
|
|
|
LayoutParams params = new LayoutParams(0, LayoutParams.WRAP_CONTENT, 1);
|
|
yearPicker.setLayoutParams(params);
|
|
monthPicker.setLayoutParams(params);
|
|
dayPicker.setLayoutParams(params);
|
|
|
|
addView(yearPicker);
|
|
addView(monthPicker);
|
|
addView(dayPicker);
|
|
|
|
// 初始化年份范围
|
|
int currentYear = Calendar.getInstance().get(Calendar.YEAR);
|
|
yearPicker.setMinValue(currentYear - 50);
|
|
yearPicker.setMaxValue(currentYear + 50);
|
|
|
|
// 月份从 1 到 12
|
|
monthPicker.setMinValue(1);
|
|
monthPicker.setMaxValue(12);
|
|
monthPicker.setOnValueChangedListener((picker, oldVal, newVal) -> updateDays());
|
|
|
|
// 默认天数范围
|
|
dayPicker.setMinValue(1);
|
|
dayPicker.setMaxValue(maxDay);
|
|
}
|
|
|
|
private void updateDays() {
|
|
int year = yearPicker.getValue();
|
|
int month = monthPicker.getValue();
|
|
|
|
int daysInMonth;
|
|
if (month == 4 || month == 6 || month == 9 || month == 11) {
|
|
daysInMonth = 30;
|
|
} else if (month == 2) {
|
|
daysInMonth = isLeapYear(year) ? 29 : 28;
|
|
} else {
|
|
daysInMonth = 31;
|
|
}
|
|
|
|
int currentDay = dayPicker.getValue();
|
|
dayPicker.setMaxValue(daysInMonth);
|
|
if (currentDay > daysInMonth) {
|
|
dayPicker.setValue(daysInMonth);
|
|
}
|
|
}
|
|
|
|
private boolean isLeapYear(int year) {
|
|
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
|
|
}
|
|
|
|
public void init(int year, int month, int day) {
|
|
yearPicker.setValue(year);
|
|
monthPicker.setValue(month + 1); // Calendar 是 0-based
|
|
dayPicker.setValue(day);
|
|
updateDays();
|
|
}
|
|
|
|
public int getYear() {
|
|
return yearPicker.getValue();
|
|
}
|
|
|
|
public int getMonth() {
|
|
return monthPicker.getValue() - 1; // 转回 Calendar 的 0-based
|
|
}
|
|
|
|
public int getDay() {
|
|
return dayPicker.getValue();
|
|
}
|
|
} |